Python/MySQL查询错误: `Unknown column`

标签 python mysql command-line mysql-connector

此脚本旨在充当命令行前端,将记录添加到本地托管的 MySQL 数据库。

我收到这个错误:

mysql.connector.errors.ProgrammingError: 1054 (42S22): 'field list' 中的未知列 'watermelon'

但是西瓜是我要输入的值,不是列名!

这是脚本:

#! /usr/bin/python

#use command line as front end to enter new rows into locally hosted mysql database

import mysql.connector

#create inputs
new_fruit = raw_input('What fruit do you want to add? ')
new_fruit_type = raw_input('Which type of ' + new_fruit + '? ')

#connect to dbase
conn = mysql.connector.connect(user='root', password='xxxx', database='play')

#instansiate cursor
cursor = conn.cursor()

#define sql statement
add_record = "INSERT INTO fruit (name, variety) VALUES (%s, %s)" % (new_fruit, new_fruit_type)

#execute sql
cursor.execute(add_record)

#close out
conn.commit()
cursor.close()
conn.close()

和表架构:

mysql> describe fruit;
+---------+----------+------+-----+---------+----------------+
| Field   | Type     | Null | Key | Default | Extra          |
+---------+----------+------+-----+---------+----------------+
| id      | int(11)  | NO   | PRI | NULL    | auto_increment |
| name    | char(30) | YES  |     | NULL    |                |
| variety | char(30) | YES  |     | NULL    |                |
+---------+----------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

最佳答案

"INSERT INTO fruit (name, variety) VALUES (%s, %s)" % ("watermelon", "melon")

字面意思是

INSERT INTO fruit (name, variety) VALUES (watermelon, melon)

watermelonmelon 不是字符串,而是列。要解决此问题,请在 %s 周围加上引号。

"INSERT INTO fruit (name, variety) VALUES ('%s', '%s')" % (new_fruit, new_fruit_type)

但是,您应该将其运行为:

cursor.execute("INSERT INTO fruit (name, variety) VALUES (%s, %s)", (new_fruit, new_fruit_type));

请注意,我们去掉了 %s 周围的引号,并将变量作为第二个参数传递给 execute 方法。 Execute 防止变量中的 sql 注入(inject),并将字符串用引号引起来。

有关详细信息,请参阅 http://mysql-python.sourceforge.net/MySQLdb.html#some-examples

关于Python/MySQL查询错误: `Unknown column` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19544015/

相关文章:

mysql - 查询在mysql中创建触发器

MySQL 联合性能问题

xcode - 为什么 Homebrew 报告 "couldn' t 理解 kern.osversion `14.0.0'”?

command-line - 使用 xdebug 和 netbeans 调试 php-cli 脚本?

python - tensorflow : Graph is finalized and cannot be modified

python - 优化遍历 numpy 数组

python - 如何折叠 Pandas 数据框? (数据透视表)

python - 创建一个在两列之间具有 bool 条件的表

mysql - 使用 group by 计算行数并显示所有行 MYSQL PHP

java - Linux 下 Runtime.getRuntime().exec() 的 Keytool 用法