4

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

2
  • 1
    Please also mention the library you are to make connection with postgres. Is it PyODBC? Commented Nov 23, 2016 at 11:41
  • 4
    Possible duplicate of postgreSQL function for last inserted ID Commented Nov 23, 2016 at 11:41

1 Answer 1

4

Pls try that:

cursor.execute("INSERT INTO .... RETURNING
id_of_new_row = cursor.fetchone()[0]
Sign up to request clarification or add additional context in comments.

1 Comment

It should be cursor.execute("INSERT INTO .... RETURNING primary_key_field_name;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.