Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy: getting the id of the last record inserted

I am using SQLAlchemy without the ORM, i.e. using hand-crafted SQL statements to directly interact with the backend database. I am using PG as my backend database (psycopg2 as DB driver) in this instance - I don't know if that affects the answer.

I have statements like this,for brevity, assume that conn is a valid connection to the database:

conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)")

Assume also that the user table consists of the columns (id [SERIAL PRIMARY KEY], name, country_id)

How may I obtain the id of the new user, ideally, without hitting the database again?

like image 974
Homunculus Reticulli Avatar asked Dec 21 '11 12:12

Homunculus Reticulli


4 Answers

You might be able to use the RETURNING clause of the INSERT statement like this:

result = conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)                        RETURNING *") 

If you only want the resulting id:

result = conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)                         RETURNING id") [new_id] = result.fetchone() 
like image 176
Erwin Brandstetter Avatar answered Oct 04 '22 15:10

Erwin Brandstetter


User lastrowid

result = conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)") result.lastrowid 
like image 33
Nilesh Avatar answered Oct 04 '22 14:10

Nilesh


Current SQLAlchemy documentation suggests

result.inserted_primary_key should work!

like image 38
Milind Dalvi Avatar answered Oct 04 '22 15:10

Milind Dalvi


Python + SQLAlchemy

after commit, you get the primary_key column id (autoincremeted) updated in your object.

db.session.add(new_usr)
db.session.commit() #will insert the new_usr data into database AND retrieve id
idd = new_usr.usrID # usrID is the autoincremented primary_key column. 
return jsonify(idd),201 #usrID = 12, correct id from table User in Database.
like image 34
Arthur Zennig Avatar answered Oct 04 '22 14:10

Arthur Zennig