import MySQLdb
import random
db = MySQLdb.connect (host = "localhost", user = "python-test", passwd = "python", db = "python-test")
cursor = db.cursor()
var = .3
sql = "INSERT INTO RandomInt
(RAND)
VALUES
(var)" # RandomInt is the name of the table and Rand is the Column Name
cursor.execute(sql)
db.commit()
db.close()
我收到一条错误消息说 Operational Error: (1054, "Unknown column 'var' in 'field list'")
为什么我会收到此错误以及如何解决此问题,尽管我已经定义变量?
最佳答案
如所写,var
将作为字符串发送到 MySQL。
试一试:
sql = "INSERT INTO RandomInt (RAND) VALUES (%s)"
cursor.execute(sql, (var,))
编辑:
>>> import MySQLdb
>>> MySQLdb.paramstyle
'format'
MySQLdb的paramstyle是format
;其中,根据 DB-API是 %s
:
'format' ANSI C printf format codes, e.g. '...WHERE name=%s'
关于Python:MySQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3327188/