SqlAlchemy: getting the id of the last record inserted

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

    User lastrowid

    result = conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)")
    result.lastrowid
    
    0 讨论(0)
  • 2021-02-05 02:04
    result.inserted_primary_key
    

    Worked for me. The only thing to note is that this returns a list that contains that last_insert_id.

    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2021-02-05 02:08

    Current SQLAlchemy documentation suggests

    result.inserted_primary_key should work!

    0 讨论(0)
  • 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.
    
    0 讨论(0)
提交回复
热议问题