Python / MySQL查询错误:`未知列`

时间:2013-10-23 14:07:25

标签: python mysql command-line mysql-connector

此脚本用作命令行前端,以将记录添加到本地托管的MySQL数据库。

我收到此错误:

mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'watermelon' in 'field list'

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

这是脚本:

#! /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)

2 个答案:

答案 0 :(得分:5)

"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以及用引号包装字符串。

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

答案 1 :(得分:0)

问题在于:

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

想象一下这会产生的查询:

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

这些价​​值不再是价值了!它们看起来更像列引用(Unknown column 'watermelon' in 'field list'

相反,您应该使用预准备语句:

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

这会自动为您完成参数设置,并会阻止SQL Injection