使用psycopg2插入多行
问题内容:
根据psycopg2:用一个查询插入多行,使用psycopg2的execute而不是executemany效率更高。其他人可以确认吗?
上面的StackOverflow问题建议使用mogrify创建此类语句:
INSERT INTO table VALUES (value1, value2), (value3, value4)
是否可以使用常规execute函数生成这样的语句?我认为某种形式
cursor.execute("""INSERT INTO table VALUES (%s, %s), (%s, %s)""", ((value1,value2),(value3,value4)))
会工作。
更新:
例如,我尝试传递执行sql语句:
insert into history (timestamp) values (%s),(%s);
与以下元组:
(('2014-04-27 14:07:30.000000',), ('2014-04-27 14:07:35.000000',))
但是我得到的只是错误:
没有要提取的结果
问题答案:
要使用execute方法,将要插入的数据放入列表中。列表将由psycopg2调整为数组。然后取消嵌套该数组并根据需要强制转换值
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()
不确定与executemany的性能差异是否很大。但我认为以上方法更加整洁。returning
顾名思义,该子句将返回插入的元组。
BTWtimestamp
是保留字,不应用作列名。