psycopg2: insert multiple rows with one query

后端 未结 15 2497
谎友^
谎友^ 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 10:00

    A snippet from Psycopg2's tutorial page at Postgresql.org (see bottom):

    A last item I would like to show you is how to insert multiple rows using a dictionary. If you had the following:

    namedict = ({"first_name":"Joshua", "last_name":"Drake"},
                {"first_name":"Steven", "last_name":"Foo"},
                {"first_name":"David", "last_name":"Bar"})
    

    You could easily insert all three rows within the dictionary by using:

    cur = conn.cursor()
    cur.executemany("""INSERT INTO bar(first_name,last_name) VALUES (%(first_name)s, %(last_name)s)""", namedict)
    

    It doesn't save much code, but it definitively looks better.

提交回复
热议问题