Python/MySQL query error: `Unknown column`

孤人 提交于 2019-12-01 09:07:43
Nathanial
"INSERT INTO fruit (name, variety) VALUES (%s, %s)" % ("watermelon", "melon")

Literally becomes

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

Instead of strings, watermelon and melon are columns. To fix this, put quotes around your %s.

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

However, you should run it as:

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

Notice we took away the quotations around the %s and are passing the variables as the second argument to the execute method. Execute prevents sql injection from the variables as well as wraps strings in quotation marks.

For more information, see http://mysql-python.sourceforge.net/MySQLdb.html#some-examples

The issue is here:

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

Imagine the query this would produce:

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

Those values aren't values anymore! They look more like column references (Unknown column 'watermelon' in 'field list')

Instead, you should use prepared statements:

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

This will automatically take care of the parameterization for you, and will prevent SQL Injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!