Python 在PostgreSQL中插入值列表
我试图在PostgreSQL数据表中插入一个值列表 我有一个名为Python 在PostgreSQL中插入值列表,python,postgresql,python-3.x,Python,Postgresql,Python 3.x,我试图在PostgreSQL数据表中插入一个值列表 我有一个名为rows的数组,它显示如下内容: for row in rows: print(row) (249607, 15802) (249612, 15802) (249613, 15802) (249614, 15802) (249615, 15802) (249616, 15802) (249617, 15802) (249619, 15802) (249620, 15802) for row in rows:
rows
的数组,它显示如下内容:
for row in rows:
print(row)
(249607, 15802)
(249612, 15802)
(249613, 15802)
(249614, 15802)
(249615, 15802)
(249616, 15802)
(249617, 15802)
(249619, 15802)
(249620, 15802)
for row in rows:
cur.execute("INSERT INTO myTable (id1, id2, key, value) \
VALUES (%s, %s, %s, %s)" , (row[0], row[1], "done", var3))
conn.commit()
我正试图像这样将其插入我的表中:
for row in rows:
print(row)
(249607, 15802)
(249612, 15802)
(249613, 15802)
(249614, 15802)
(249615, 15802)
(249616, 15802)
(249617, 15802)
(249619, 15802)
(249620, 15802)
for row in rows:
cur.execute("INSERT INTO myTable (id1, id2, key, value) \
VALUES (%s, %s, %s, %s)" , (row[0], row[1], "done", var3))
conn.commit()
不幸的是,它只插入了一行。我做错了什么?如果有人仍在寻找答案,我将使用新的
psycopg2.extras.execute\u batch()
方法:
mydict = map(lambda x : {'row0':x[0], 'row1':x[1], 'done':'done', 'var3':var3}, rows)
query = """INSERT INTO myTable (id1, id2, key, value) \
VALUES (%(row0)s, %(row1)s, %(done)s, %(var3)s)"""
psycopg2.extras.execute_batch(cur, query, mydict)
看起来键值是一个常量,所以您只获取最后一组值,而这一行是插入元组的?第一个还是最后一个?检查表上的约束-任何非null、主/外部/复合键等可能需要使用
try/catch
包装以输出任何异常。可能我已经在表中设置了键。有一些简单的方法可以检查它是否存在以进行更新,如果不插入?