Predict next auto-inserted row id (SQLite)

前端 未结 11 1319
予麋鹿
予麋鹿 2020-12-03 17:23

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 anoth

11条回答
  •  有刺的猬
    2020-12-03 17:46

    I realize your application using SQLite is small and SQLite has its own semantics. Other solutions posted here may well have the effect that you want in this specific setting, but in my view every single one of them I have read so far is fundamentally incorrect and should be avoided.

    In a normal environment holding a transaction for user input should be avoided at all costs. The way to handle this, if you need to store intermediate data, is to write the information to a scratch table for this purpose and then attempt to write all of the information in an atomic transaction. Holding transactions invites deadlocks and concurrency nightmares in a multi-user environment.

    In most environments you cannot assume data retrieved via SELECT within a transaction is repeatable. For example

    SELECT Balance FROM Bank ...
    UPDATE Bank SET Balance = valuefromselect + 1.00 WHERE ...
    

    Subsequent to UPDATE the value of balance may well be changed. Sometimes you can get around this by updating the row(s) your interested in Bank first within a transaction as this is guaranteed to lock the row preventing further updates from changing its value until your transaction has completed.

    However, sometimes a better way to ensure consistency in this case is to check your assumptions about the contents of the data in the WHERE clause of the update and check row count in the application. In the example above when you "UPDATE Bank" the WHERE clause should provide the expected current value of balance:

    WHERE Balance = valuefromselect
    

    If the expected balance no longer matches neither does the WHERE condition -- UPDATE does nothing and rowcount returns 0. This tells you there was a concurrency issue and you need to rerun the operation again when something else isn't trying to change your data at the same time.

提交回复
热议问题