Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting Autoincrement in Android SQLite

Tags:

android

sqlite

I have this method which will remove all rows from a table but I also want it to reset the autoincrement so that when a new row is added it will start again. The SQL statement I'm using isn't working due to certain columns not existing. Am I doing it right?

private void rmvAll() {

    SQLiteDatabase db = appts.getWritableDatabase();
    db.delete(TABLE_NAME, null, null);
    db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = " + TABLE_NAME);

}
like image 352
nexus490 Avatar asked Mar 18 '12 15:03

nexus490


People also ask

How do you Autoincrement in SQLite?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment. The keyword AUTOINCREMENT can be used with INTEGER field only.

How can reset primary key ID after delete the row?

ALTER TABLE `table` AUTO_INCREMENT = number; Replacing 'number' with the result of the previous command plus one and replacing table with the table name. If you deleted all the rows in the table, then you could run the alter table command and reset it to 0.

How do I delete a sequence in SQLite?

#Deleting the Table Number Sequence. DELETE FROM `sqlite_sequence` WHERE `name` = 'table_name'; If a table sequence is deleted from the sqlite_sequence table (or it doesn't exist), SQLite would use the next available number for the ROWID when a new row is inserted in that table.

What is integer primary key autoincrement?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.


2 Answers

you'll need single quotes around your table name, i.e.

db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME + "'");
like image 200
dldnh Avatar answered Oct 13 '22 00:10

dldnh


Building on dldnh's answer:

The following query will set seq to the largest value in the col identity column in the Tbl table, so there is no risk of violating constraints.

UPDATE sqlite_sequence SET seq = (SELECT MAX(col) FROM Tbl) WHERE name="Tbl"
like image 39
Trisped Avatar answered Oct 12 '22 23:10

Trisped