How to retrieve inserted id after inserting row in SQLite using Python? I have table like this:
id INT AUTOINCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50)
I insert a new row with example data username="test"
and password="test"
. How do I retrieve the generated id in a transaction safe way? This is for a website solution, where two people may be inserting data at the same time. I know I can get the last read row, but I don't think that is transaction safe. Can somebody give me some advice?
You could use cursor.lastrowid (see "Optional DB API Extensions"):
If two people are inserting at the same time, as long as they are using different
cursor
s,cursor.lastrowid
will return theid
for the last row thatcursor
inserted:Note that
lastrowid
returnsNone
when you insert more than one row at a time withexecutemany
: