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,为什么会出现此错误,以及如何解决此错误? 最佳答案
如所写,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 - Python:MySQL中的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3327188/