I am using SQLite3 and Python 3. I need to select the primary key value of a newly inserted record. The primary keys are autoincremented, I prefer to keep it that way (rather than generating primary keys myself and keeping track of them in Python). I do this in two steps (SELECT
after INSERT
) but want it in a single step for efficiency, using a JOIN
.
Using cursor.lastrowid
is faster than two execute
statements (timeit
uses linked example):
$ python -m timeit -s "\
> import sqlite3;\
> connection=sqlite3.connect(':memory:');\
> cursor=connection.cursor();\
> cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,\
> username varchar(50),\
> password varchar(50))''')" "\
> cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',\
> ('test','test'));\
> found = cursor.execute('''SELECT id FROM foo \
> WHERE username='test' \
> AND password='test' ''')"
100000 loops, best of 3: 10.1 usec per loop
$
$ python -m timeit -s "\
> import sqlite3;\
> connection=sqlite3.connect(':memory:');\
> cursor=connection.cursor();\
> cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,\
> username varchar(50),\
> password varchar(50))''')" "\
> cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',\
> ('test','test'));\
> found = cursor.lastrowid"
100000 loops, best of 3: 5.74 usec per loop
$
How to do this as a JOIN
instead, so it is still involves a single execute
but is strictly limited to SQL commands?