I’m using sqlite3 and would like to know, if there is a fast way to retrieve the primary key created during the last insert statement in table A, so I can use it as foreign key for different insert statement in table B. For example, first add a new car brand in one table, then add some models of the brand in a different table.
TABLE car_brands (
brandID INTEGER PRIMARY KEY NOT NULL,
name TEXT
)
TABLE car_models (
modelID INTEGER PRIMARY KEY NOT NULL,
brandID INTEGER REFERENCES brandID,
name TEXT
)
sqlite3_last_insert_rowid() is no option, since I do not know if another thread is updating the database during this operation.
Will I have to retrieve it using a separate statement?
Greetings,
curiosity
According to the online help, both
sqlite3_last_insert_rowid()andlast_insert_rowid()(for use within SQL) are connection specific.As long as you ensure multiple threads are not sharing the same connection, you won’t get concurrency issues with
sqlite3_last_insert_rowid().And within your SQL statements, one connection can only be running one query. Provided you have both the INSERT and the call to
last_insert_rowid()within the same batch, that shouldn’t have concurrency issues either.