"INSERT INTO fruit (name, variety) VALUES (%s, %s)" % ("watermelon", "melon")
从字面上看就变成了
INSERT INTO fruit (name, variety) VALUES (watermelon, melon)
而不是字符串,watermelon
and melon
是列。要解决此问题,请在您的%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 http://mysql-python.sourceforge.net/MySQLdb.html#some-examples