I\'d like to use psycopg2 to INSERT
multiple rows and then return all the id
s (in order) using a single query. This is what PostgreSQL\'s RET
Pass the dynamically-generated data as an array of tuples and unnest it
import psycopg2
insert = """
insert into my_table (field_1, field_2)
select field_1, field_2
from unnest(%s) s(field_1 int, field_2 int)
returning id
;"""
data = [(0,0),(1,1),(2,2)]
conn = psycopg2.connect("host=localhost4 port=5432 dbname=cpn")
cursor = conn.cursor()
cursor.execute(insert, (data,))
print cursor.fetchall()
conn.commit()
conn.close()
Prints
[(1,), (2,), (3,)]