psycopg2: insert multiple rows with one query

后端 未结 15 2502
谎友^
谎友^ 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:48

    cursor.copy_from is the fastest solution I've found for bulk inserts by far. Here's a gist I made containing a class named IteratorFile which allows an iterator yielding strings to be read like a file. We can convert each input record to a string using a generator expression. So the solution would be

    args = [(1,2), (3,4), (5,6)]
    f = IteratorFile(("{}\t{}".format(x[0], x[1]) for x in args))
    cursor.copy_from(f, 'table_name', columns=('a', 'b'))
    

    For this trivial size of args it won't make much of a speed difference, but I see big speedups when dealing with thousands+ of rows. It will also be more memory efficient than building a giant query string. An iterator would only ever hold one input record in memory at a time, where at some point you'll run out of memory in your Python process or in Postgres by building the query string.

提交回复
热议问题