psycopg2:通过一个查询插入多行 [英] psycopg2: insert multiple rows with one query

查看:113
本文介绍了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分钟:

cur.executemany("INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)", tup)

这篇关于psycopg2:通过一个查询插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆