我有这个代码:
sql = r"INSERT INTO table(par1,par2) VALUES ('%s',%d)
ON DUPLICATE KEY UPDATE par2=par2+VALUES(par2)"
(主键是 par1) 和一个看起来像这样的Python字典
dict = {'http://smth.com': 3,
'http://smth2.com': 4}
第一个值是字符串,另一个是数字。 当我尝试执行cursor.executemany(sql, dict) 时,它会引发此错误:
TypeError: %d format: a number is required, not str
我能做什么?
最佳答案
字典上的默认迭代器仅产生字典键,例如:
for k in dict(a=1, b=2, c=3):
print k
只会打印“a”、“b”和“c”,而您需要键和值来进行sql替换。
改用iteritems
,这些会产生“完整”(键,值)对:
cursor.executemany(sql, dict.iteritems())
参见: http://docs.python.org/2/library/stdtypes.html#dict.iteritems
顺便说一句,根据:
http://mysql-python.sourceforge.net/MySQLdb.html#some-examples
您的格式说明符可能都应该是纯 %s
。
关于python - Mysql,对字典中的数据执行所有命令。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21329363/