python - Mysql,对字典中的数据执行所有命令。 Python

标签 python mysql dictionary

我有这个代码:

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/

相关文章:

Python计算阶乘,OverflowError : int too large to convert to float

python - 使用 Python 获取视频中的 I 帧列表

python - django 二进制文件下载在浏览器中损坏

Mysql Group by 3个带计数的字段

python - 如何按嵌套字典中的元素访问 pandas 多重索引?

python - Python 如何推断二进制 NOT 中使用的位数?

php - 在事务数据库上使用什么 mysql 扩展

javascript - 如何使用 Node js 和 html 构建客户端服务器应用程序?

Scala 在迭代时更新映射中的值

python - 基于字典键值和字符串编号的列表排序