SqlAlchemy: getting the id of the last record inserted

后端 未结 7 910
[愿得一人]
[愿得一人] 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:08

    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()
    

提交回复
热议问题