SqlAlchemy: getting the id of the last record inserted

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

    this question has been asked many times on stackoverflow and no answer I have seen is comprehensive. Googling 'sqlalchemy insert get id of new row' brings up a lot of them.

    There are three levels to SQLAlchemy. Top: the ORM. Middle: Database abstraction (DBA) with Table classes etc. Bottom: SQL using the text function.

    To an OO programmer the ORM level looks natural, but to a database programmer it looks ugly and the ORM gets in the way. The DBA layer is an OK compromise. The SQL layer looks natural to database programmers and would look alien to an OO-only programmer.

    Each level has it own syntax, similar but different enough to be frustrating. On top of this there is almost too much documentation online, very hard to find the answer.

    I will describe how to get the inserted id AT THE SQL LAYER for the RDBMS I use.

    Table: User(user_id integer primary autoincrement key, user_name string)
    conn: Is a Connection obtained within SQLAlchemy to the DBMS you are using.
    
    
    SQLite
    ======
    insstmt = text(
        '''INSERT INTO user (user_name)
        VALUES (:usernm) ''' )
    # Execute within a transaction (optional)
    txn = conn.begin()
    result = conn.execute(insstmt, usernm='Jane Doe')
    # The id!
    recid = result.lastrowid
    txn.commit()
    
    
    MS SQL Server
    =============
    insstmt = text(
        '''INSERT INTO user (user_name) 
        OUTPUT inserted.record_id
        VALUES (:usernm) ''' )
    txn = conn.begin()
    result = conn.execute(insstmt, usernm='Jane Doe')
    # The id!
    recid = result.fetchone()[0]
    txn.commit()
    
    
    MariaDB/MySQL
    =============
    insstmt = text(
        '''INSERT INTO user (user_name)
        VALUES (:usernm) ''' )
    txn = conn.begin()
    result = conn.execute(insstmt, usernm='Jane Doe')
    # The id!
    recid = conn.execute(text('SELECT LAST_INSERT_ID()')).fetchone()[0]
    txn.commit()
    
    
    Postgres
    ========
    insstmt = text(
        '''INSERT INTO user (user_name)
        VALUES (:usernm) 
        RETURNING user_id ''' )
    txn = conn.begin()
    result = conn.execute(insstmt, usernm='Jane Doe')
    # The id!
    recid = result.fetchone()[0]
    txn.commit()
    

提交回复
热议问题