我正在尝试将一些值插入到我的表中。代码是:
import MySQLdb
db=MySQLdb.connect(host="localhost",user="user_name", passwd="",db="name_of_db", port=3306)
cursor=db.cursor()
readcount=52
sql="Insert into pressure_image(idItem, pressure_val, image_loc, array_time, Time_Stamp) values ('%d', 260, 'a.jpg', 'aray', 14-11-2000)"
try:
cursor.execute(sql, (readcount))
db.commit()
except:
print "No value inserted"
db.rollback()
问题是当我尝试插入命令时,例如:
sql="插入压力_image(idItem、压力_val、image_loc、array_time、Time_Stamp)值(30, 260, 'a.jpg', 'aray', 14-11-2000)"
这些值已正确插入表中,但是当我尝试代码中给出的命令时,没有插入任何值。因此本质上,常量有效,但变量则无效。
如何将变量插入表中?
最佳答案
尝试添加逗号:
cursor.execute(sql, (readcount,))
这里(readcount) == readcount
,但是(readcount,)
是一个包含 readcount
的元组。
同时将查询中的 %d
替换为 %s
。
正如 documentation 中所述
execute(self, query, args=None)
query - string, query to execute on server
args - optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then
%s
must be used as the parameter placeholder in the query. If a mapping is used,%(key)s
must be used as the placeholder.
因此,MySQLdb 强制我们对 args
参数(可以是任何可迭代类型)和 %s
使用序列。使用 %s
格式说明符是因为在格式化查询之前,args
中的值会被转义并转换为字符串。
关于python - MySQL 和 Python-插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23082932/