Python/postgres/psycopg2: getting ID of row just inserted
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping
--
Chapters
00:00 Python/Postgres/Psycopg2: Getting Id Of Row Just Inserted
00:39 Accepted Answer Score 324
01:08 Answer 2 Score 18
01:31 Answer 3 Score 7
01:42 Answer 4 Score 5
02:19 Answer 5 Score 4
02:45 Thank you
--
Full question
https://stackoverflow.com/questions/5247...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #postgresql #psycopg2
#avk47
ACCEPTED ANSWER
Score 325
cursor.execute("INSERT INTO .... RETURNING id")
id_of_new_row = cursor.fetchone()[0]
And please do not build SQL strings containing values manually. You can (and should!) pass values separately, making it unnecessary to escape and SQL injection impossible:
sql_string = "INSERT INTO domes_hundred (name,name_slug,status) VALUES (%s,%s,%s) RETURNING id;"
cursor.execute(sql_string, (hundred_name, hundred_slug, status))
hundred = cursor.fetchone()[0]
See the psycopg docs for more details: http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries
ANSWER 2
Score 18
I ended up here because I had a similar problem, but we're using Postgres-XC, which doesn't yet support the RETURNING ID clause. In that case you can use:
cursor.execute('INSERT INTO ........')
cursor.execute('SELECT LASTVAL()')
lastid = cursor.fetchone()['lastval']
Just in case it was useful for anyone!
ANSWER 3
Score 7
Consider a RETURNING clause http://www.postgresql.org/docs/8.3/static/sql-insert.html
ANSWER 4
Score 5
For me, neither ThiefMaster's answer worked nor Jamie Brown's. What worked for me was a mix of both, and I'd like to answer here so it can help someone else.
What I needed to do was:
cursor.execute('SELECT LASTVAL()')
id_of_new_row = cursor.fetchone()[0]
The statement lastid = cursor.fetchone()['lastval'] didn't work for me, even after cursor.execute('SELECT LASTVAL()'). The statement id_of_new_row = cursor.fetchone()[0] alone didn't work either.
Maybe I'm missing something.