简体   繁体   English

使用psycopg2插入多行

[英]Inserting multiple rows using psycopg2

According to psycopg2: insert multiple rows with one query , it is much more efficient to use psycopg2's execute instead of executemany . 根据psycopg2:使用一个查询插入多行,使用psycopg2的execute而不是executemany效率更高 Can others confirm? 其他人可以确认吗?

The above StackOverflow question suggests using mogrify for creating statements of the sort: 上面的StackOverflow问题建议使用mogrify创建此类语句:

INSERT INTO table VALUES (value1, value2), (value3, value4)

Is it possible to generate such a statement using the regular execute function? 是否可以使用常规execute函数生成这样的语句? I thought something of the form 我认为某种形式

cursor.execute("""INSERT INTO table VALUES (%s, %s), (%s, %s)""", ((value1,value2),(value3,value4)))

would work. 会工作。

UPDATE: 更新:

For instance, I tried I passing into execute the sql statement: 例如,我尝试传递执行sql语句:

insert into history (timestamp) values (%s),(%s); 

with the folowing tuple: 与以下元组:

(('2014-04-27 14:07:30.000000',), ('2014-04-27 14:07:35.000000',))

but all I got back was the error: 但是我得到的只是错误:

no results to fetch 没有要获取的结果

To use the execute method place the data to be inserted in a list. 要使用execute方法,将要插入的数据放入列表中。 A list will be adapted by psycopg2 to an array. 一个列表将由psycopg2调整为数组。 Then you unnest the array and cast the values as necessary 然后您取消嵌套数组并根据需要强制转换值

import psycopg2

insert = """
    insert into history ("timestamp")
    select value
    from unnest(%s) s(value timestamp)
    returning *
;"""

data = [('2014-04-27 14:07:30.000000',), ('2014-04-27 14:07:35.000000',)]
conn = psycopg2.connect("host=localhost4 port=5432 dbname=cpn")
cursor = conn.cursor()
cursor.execute(insert, (data,))
print cursor.fetchall()
conn.commit()
conn.close()

Not sure if the performance difference from executemany will be significant. 不确定与executemany的性能差异是否很大。 But I think the above is neater. 但我认为以上方法更加整洁。 The returning clause will, as the name suggests, return the inserted tuples. 顾名思义, returning子句将返回插入的元组。

BTW timestamp is a reserved word and should not be used as a column name. BTW timestamp是保留字,不应用作列名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM