我有一行字典格式的数据。有没有一种简单的方法可以将它插入到 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)
其中 key1
、key2
等将是字典中的键。
免责声明:我自己还没有尝试过:)
编辑:是的,试过了。它有效。
关于python - MySQLdb 将字典插入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8674426/