-1

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.

Frank Harris
  • 587
  • 2
  • 16
  • Please check this https://stackoverflow.com/questions/7737899/python-sqlite-get-pk-of-newly-inserted-row – tbhaxor Feb 17 '22 at 17:55

1 Answers1

0

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.
ilias-sp
  • 6,135
  • 4
  • 28
  • 41
  • Hi, thanks, I'm not clear on the syntax for this, and the documentation doesn't provide examples. If I set the last line to `return db.lastrowid` I get that there's no such attribute. What I have seen is that it's used with a cursor, which I'm not using. I've followed a tutorial which initializes the db object with `g.db = sqlite3.connect(...)`, and then just running `db.execute(...)`. Is there an implicit cursor with the way I'm doing it, or a way to access the cursor? I tried `db.cursor().lastrowid` but that's just None. – Frank Harris Feb 17 '22 at 19:59