小编Paa*_*and的帖子

Psycopg2在postgres数据库中插入python字典

在python 3+中,我想将字典(或pandas数据帧)中的值插入数据库.我选择了带有postgres数据库的psycopg2.

问题是我无法找到正确的方法来做到这一点.我可以轻松地连接要执行的SQL字符串,但psycopg2文档明确警告不要这样做.理想情况下我想做这样的事情:

cur.execute("INSERT INTO table VALUES (%s);", dict_data)
Run Code Online (Sandbox Code Playgroud)

并希望执行可以弄清楚dict的键与表中的列匹配.这没用.从psycopg2文档的例子我得到了这种方法

cur.execute("INSERT INTO table (" + ", ".join(dict_data.keys()) + ") VALUES (" + ", ".join(["%s" for pair in dict_data]) + ");", dict_data)
Run Code Online (Sandbox Code Playgroud)

我得到了一个

TypeError: 'dict' object does not support indexing
Run Code Online (Sandbox Code Playgroud)

将字典插入到具有匹配列名的表中的最为植物方式是什么?

postgresql dictionary psycopg2 python-3.x

1
推荐指数
1
解决办法
6029
查看次数

标签 统计

dictionary ×1

postgresql ×1

psycopg2 ×1

python-3.x ×1