Predict next auto-inserted row id (SQLite)

前端 未结 11 1321
予麋鹿
予麋鹿 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:57

    Most likely you should be able to +1 the most recent id. I would look at all (going back a while) of the existing id's in the ordered table .. Are they consistent and is each row's ID is one more than the last? If so, you'll probably be fine. I'd leave a comments in the code explaining the assumption however. Doing a Lock will help guarantee that you're not getting additional rows while you do this as well.

    0 讨论(0)
  • 2020-12-03 17:57

    Most of everything that needs to be said in this topic already has... However, be very careful of race conditions when doing this. If two people both open your application/webpage/whatever, and one of them adds a row, the other user will try to insert a row with the same ID and you will have lots of issues.

    0 讨论(0)
  • 2020-12-03 17:58

    Try SELECT * FROM SQLITE_SEQUENCE WHERE name='TABLE';. This will contain a field called seq which is the largest number for the selected table. Add 1 to this value to get the next ID.

    Also see the SQLite Autoincrement article, which is where the above info came from.

    Cheers!

    0 讨论(0)
  • 2020-12-03 17:59

    Select the last_insert_rowid() value.

    0 讨论(0)
  • 2020-12-03 18:03

    I think this can't be done because there is no way to be sure that nothing will get inserted between you asking and you inserting. (you might be able to lock the table to inserts but Yuck)

    BTW I've only used MySQL but I don't think that will make any difference)

    0 讨论(0)
提交回复
热议问题