Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the “id” after INSERT into a postgres database with Python?

I am doing an INSERT into a postgres DB, which has an auto increment field called id.

How do I get the value of id after doing the insert in Python? There are good references on this site to this for MySQL databases (i.e. using cursor.lastrowid, or connection.insert_id()) but these don't seem to work with my postgres DB.

The id field is using a sequence to auto increment. So the id field is not null, default, nextval('table_id_seq')

Thanks

like image 997
Simon Avatar asked Oct 28 '25 08:10

Simon


1 Answers

Pls try that:

cursor.execute("INSERT INTO .... RETURNING
id_of_new_row = cursor.fetchone()[0]
like image 89
user1208486 Avatar answered Oct 31 '25 03:10

user1208486



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!