使用psycopg2插入多行

2024-04-19 16:02:33 发布

您现在位置:Python中文网/ 问答频道 /正文

根据psycopg2: insert multiple rows with one query,使用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)))

会有用的。

更新:

例如,我试着传入execute the sql语句:

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

用下面的元组:

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

但我得到的只是一个错误:

no results to fetch


Tags: executewithtable语句multiplepsycopg2rowsinsert
1条回答
网友
1楼 · 发布于 2024-04-19 16:02:33

要使用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是保留字,不应用作列名。

相关问题 更多 >