将元组插入表 - psycopg2

时间:2014-11-28 16:47:26

标签: python postgresql psycopg2

我试图弄清楚如何将一组值插入预定义表中而不需要像以下那样简单的语法:

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()

的麻烦

2 个答案:

答案 0 :(得分:2)

使用此表

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')

完成上述操作后,我认为不明确列出列

是不好的做法

答案 1 :(得分:0)

假设:

t = (100, "abc'def")

然后:

sql = "INSERT INTO test (num, data) VALUES (" + ",".join(["%s"]*len(t)) + ")"
cur.execute(sql, t)

即。每个字段重复占位符一次,逗号分隔。

是的,它很丑陋,但没有魔法"所有参数"通配符。也许应该有。

相关问题