使用psycopg2插入多行

0 投票
1 回答
13376 浏览
提问于 2025-04-18 04:26

根据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语句传递给execute:

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

并使用以下元组:

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

但我得到的错误是:

没有结果可获取

1 个回答

8

要使用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和execute之间的性能差异是否会很明显。不过我觉得上面的写法更整洁。returning这个部分,顾名思义,会返回你插入的数据行。

顺便提一下,timestamp是一个保留字,不应该用作列名。

撰写回答