在 python 3+ 中,我想将字典(或 pandas 数据框)中的值插入到数据库中。我选择了带有 postgres 数据库的 psycopg2。
问题是我想不出正确的方法来做到这一点。我可以很容易地连接一个 SQL 字符串来执行,但是 psycopg2 文档明确警告不要这样做。理想情况下,我想做这样的事情:
cur.execute("INSERT INTO table VALUES (%s);", dict_data)
并希望execute能够判断出字典的键与表中的列相匹配。这没有用。从 psycopg2 文档的示例中我得到了这种方法
cur.execute("INSERT INTO table (" + ", ".join(dict_data.keys()) + ") VALUES (" + ", ".join(["%s" for pair in dict_data]) + ");", dict_data)
我从中得到一个
TypeError: 'dict' object does not support indexing
将字典插入具有匹配列名的表的最自然方法是什么?
最佳答案
两种解决方案:
d = {'k1': 'v1', 'k2': 'v2'}
insert = 'insert into table (%s) values %s'
l = [(c, v) for c, v in d.items()]
columns = ','.join([t[0] for t in l])
values = tuple([t[1] for t in l])
cursor = conn.cursor()
print cursor.mogrify(insert, ([AsIs(columns)] + [values]))
keys = d.keys()
columns = ','.join(keys)
values = ','.join(['%({})s'.format(k) for k in keys])
insert = 'insert into table ({0}) values ({1})'.format(columns, values)
print cursor.mogrify(insert, d)
输出:
insert into table (k2,k1) values ('v2', 'v1')
insert into table (k2,k1) values ('v2','v1')
关于postgresql - Psycopg2 在 postgres 数据库中插入 python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39203050/