"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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…