SqlAlchemy: getting the id of the last record inserted

后端 未结 7 832
[愿得一人]
[愿得一人] 2021-02-05 01:35

I am using SQLAlchemy without the ORM, i.e. using hand crafted SQL statememts to directly interact with the backend db. I am using PG as my backend db (psycopg2 as DB driver) in

7条回答
  •  终归单人心
    2021-02-05 02:10

    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.
    

提交回复
热议问题