我试图弄清楚如何将值的元组插入到预定义的表中,而不需要像这样的简单语法:
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",
... (100, "abc'def"))
因为我的元组具有正确的值序列,如下所示:
my_tuple = ('D', 'Z107383320', '99501', '995013688', None, '36', '88', '36', '88', 'A', 'F', 'C083', '', 'BARROW', 'ST', '', '0000000605', '0000000605', 'O', 'DOCTORS COLLECTIONS SVC', 'STE', '00000001', '00000001', 'O', 'B', '', '', '020312', 'AK', '020', 'AL', '', '', 'Z10014', 'zip4mst9')
我想知道一些简单的解决方案:-)例如:
cur.execute("INSERT INTO test (*) VALUES (*)",
... (my_tuple))
由于我创建了表模式并且元组具有相同的属性序列,因此我认为这是可能的,而无需将所有参数一一传递给 cur.execute()
最佳答案
使用此表
create table t (
a int,
b text
);
省略列列表并将元组作为单个值传递
query = """
insert into t values %s
returning *
"""
my_tuple = (2, 'b')
cursor.execute(query, (my_tuple,)) # Notice the comma after my_tuple
rs = cursor.fetchall()
conn.commit()
for row in rs:
print row
打印
(2, 'b')
完成上述操作后,我认为不明确列出列是不好的做法
关于python - 将元组插入表中 - psycopg2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27193002/