I’m trying to find if there is a reliable way (using SQLite) to find the ID of the next row to be inserted, before it gets inserted. I need to use the id for another insert statement, but don’t have the option of instantly inserting and getting the next row.
Is predicting the next id as simple as getting the last id and adding one? Is that a guarantee?
Edit: A little more reasoning… I can’t insert immediately because the insert may end up being canceled by the user. User will make some changes, SQL statements will be stored, and from there the user can either save (inserting all the rows at once), or cancel (not changing anything). In the case of a program crash, the desired functionality is that nothing gets changed.
Either scrapping or committing a series of database operations all at once is exactly what transactions are for. Query
BEGIN;before the user starts fiddling andCOMMIT;once he/she’s done. You’re guaranteed that either all the changes are applied (if you commit) or everything is scrapped (if you queryROLLBACK;, if the program crashes, power goes out, etc). Once you read from the db, you’re also guaranteed that the data is good until the end of the transaction, so you can grabMAX(id)or whatever you want without worrying about race conditions.http://www.sqlite.org/lang_transaction.html