python - MySQLdb 将字典插入表中

标签 python dictionary insert mysql-python

我有一行字典格式的数据。有没有一种简单的方法可以将它插入到 mysql 表中。我知道我可以编写自定义函数来将 dict 转换为自定义 sql 查询,但我正在寻找更直接的替代方法。

最佳答案

嗯...根据paramstyle 的文档:

Set to 'format' = ANSI C printf format codes, e.g. '...WHERE name=%s'. If a mapping object is used for conn.execute(), then the interface actually uses 'pyformat' = Python extended format codes, e.g. '...WHERE name=%(name)s'. However, the API does not presently allow the specification of more than one style in paramstyle

所以,这应该只是一个问题:

curs.execute("INSERT INTO foo (col1, col2, ...) VALUES (%(key1)s, %(key2)s, ...)", dictionary)

其中 key1key2 等将是字典中的键。

免责声明:我自己还没有尝试过:)

编辑:是的,试过了。它有效。

关于python - MySQLdb 将字典插入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8674426/

相关文章:

python - 无法安装 python-chess : "UnboundLocalError: local variable ' distclass' referenced before assignment"

Python:从格式化字符串中提取字段

python - 根据正则表达式字典填充 Pandas DataFrame 列

json - 去图表动态数据

mysql - 复制一些值以在 MYSQL 中创建另一行

c++ - BST插入、删除、搜索

python - 如何从 Bash 脚本在后台运行 Python 脚本?

python - 如何在matplotlib中绘制三次样条

python - key 错误 : 'Requested level (date) does not match index name (None)'

java - 参数化批量插入到Spring JDBC中