psycopg2: insert multiple rows with one query

后端 未结 15 2505
谎友^
谎友^ 2020-11-22 09:11

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),         


        
15条回答
  •  滥情空心
    2020-11-22 09:40

    I built a program that inserts multiple lines to a server that was located in another city.

    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) 
    

    and 2 minutes when using this method:

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

提交回复
热议问题