问题
I created a table using Android's Room library, which stores items of type User
. For the ID column, the value is automatically generated by adding the annotation
@PrimaryKey(autoGenerate = true)
In the next application run, I delete all entries in the table. However, the auto-generated value is not reset to 0, but continues where it left of the previous run.
How can I reset the auto-increment counter when I delete all entries in a table?
回答1:
Why would you, is perhaps the more pertinent question. A column with AUTOINCREMENT will be an alias of the rowid column which is used to uniquely identify a row. It isn't the best practice to rely upon this value other than for identifying a row.
Using AUTOINCREMENT (autogenerate = true) results in an internal table sqlite_sequence being created, a row in that table holds the value of the highest ever used rowid The next rowid will be that values + 1. Hence your issue.
As such to restart from 1 you would have to either update the respective row in the sqlite_sequence table to 0 or delete the respective row in the sqlite_sequence table.
You may wish to have a look at Android Room - reset auto generated key on each app run. Noting that this could be the basis for resetting the sequence value, but that it will always resets the sequence value.
来源:https://stackoverflow.com/questions/53805597/reset-auto-increment-in-androids-room-library