psycopg2:用一个查询插入多行 [英] psycopg2: insert multiple rows with one query
本文介绍了psycopg2:用一个查询插入多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要用一个查询插入多行(行数不固定),所以我需要像这样执行查询:
I need to insert multiple rows with one query (number of rows is not constant), so I need to execute query like this one:
INSERT INTO t (a, b) VALUES (1, 2), (3, 4), (5, 6);
我知道的唯一方法是
args = [(1,2), (3,4), (5,6)]
args_str = ','.join(cursor.mogrify("%s", (x, )) for x in args)
cursor.execute("INSERT INTO t (a, b) VALUES "+args_str)
但我想要一些更简单的方法.
but I want some simpler way.
推荐答案
我构建了一个程序,可以将多行插入到位于另一个城市的服务器中.
I built a program that inserts multiple lines to a server that was located in another city.
我发现使用这种方法比 executemany
快 10 倍左右.在我的例子中 tup
是一个包含大约 2000 行的元组.使用这个方法大概花了10秒:
I found out that using this method was about 10 times faster than executemany
. In my case tup
is a tuple containing about 2000 rows. It took about 10 seconds when using this method:
args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str)
使用此方法时需要 2 分钟:
and 2 minutes when using this method:
cur.executemany("INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)", tup)
这篇关于psycopg2:用一个查询插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文