更新时间:2023-01-29 21:28:31
"INSERT INTO fruit (name, variety) VALUES (%s, %s)" % ("watermelon", "melon")
从字面上变得
INSERT INTO fruit (name, variety) VALUES (watermelon, melon)
watermelon
和melon
是列,而不是字符串.要解决此问题,请在您的%s
周围加上引号.
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));
注意,我们删除了%s
周围的引号,并将变量作为第二个参数传递给execute
方法. Execute
防止从变量中进行sql注入,并将字符串用引号引起来.
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.
有关更多信息,请参见 http://mysql-python.sourceforge.net /MySQLdb.html#some-examples
For more information, see http://mysql-python.sourceforge.net/MySQLdb.html#some-examples