psycopg2: insert multiple rows with one query

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

    The cursor.copyfrom solution as provided by @jopseph.sheedy (https://stackoverflow.com/users/958118/joseph-sheedy) above (https://stackoverflow.com/a/30721460/11100064) is indeed lightning fast.

    However, the example he gives are not generically usable for a record with any number of fields and it took me while to figure out how to use it correctly.

    The IteratorFile needs to be instantiated with tab-separated fields like this (r is a list of dicts where each dict is a record):

        f = IteratorFile("{0}\t{1}\t{2}\t{3}\t{4}".format(r["id"],
            r["type"],
            r["item"],
            r["month"],
            r["revenue"]) for r in records)
    

    To generalise for an arbitrary number of fields we will first create a line string with the correct amount of tabs and field placeholders : "{}\t{}\t{}....\t{}" and then use .format() to fill in the field values : *list(r.values())) for r in records:

            line = "\t".join(["{}"] * len(records[0]))
    
            f = IteratorFile(line.format(*list(r.values())) for r in records)
    

    complete function in gist here.

提交回复
热议问题