'sqlite: get row I just added [duplicate]

When I insert a new row into a table, what's the best way to get the autoincremented primary key of the row I just created? Like this:

def create_address_and_get_id(address_line_1, address_line_2, city, state_abbrev, postcode, country):
    db = get_db()
    db.execute(
        'INSERT INTO mailing_address (address_line_1, address_line_2,'
        ' city, state_abbrev, postcode, country)'
        ' VALUES (?, ?, ?, ?, ?, ?)'
        (address_line_1, address_line_2, city, state_abbrev, postcode, country)
    )
    db.commit()
    #return ???  

I've seen how to do this in other systems but not in python.



Solution 1:[1]

you are looking for the lastrowid:

https://docs.python.org/3/library/sqlite3.html:

lastrowid

    This read-only attribute provides the rowid of the last modified row. It is only set if you issued an INSERT or a REPLACE statement using the execute() method. For operations other than INSERT or REPLACE or when executemany() is called, lastrowid is set to None.

    If the INSERT or REPLACE statement failed to insert the previous successful rowid is returned.

    Changed in version 3.6: Added support for the REPLACE statement.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ilias-sp