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 RETURNING
extension is designed for, and it seems to work fine using cursor.execute
:
cursor.execute(
"INSERT INTO my_table (field_1, field_2) "
"VALUES (0, 0), (0, 0) RETURNING id;"
)
print cursor.fetchall()
[(1,), (2,)]
Now, in order to pass in dynamically-generated data, it seems like cursor.executemany
is the way to go:
data = [(0, 0), (0, 0)]
cursor.executemany(
"INSERT INTO my_table (field_1, field_2) "
"VALUES (%s, %s) RETURNING id;",
data
)
However, in that case, cursor.fetchall()
produces the following:
[(4,), (None,)]
How do I get it to correctly return all the id
s instead of just the one?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…