Android机房 - 清除sqlite_sequence无效

时间:2018-03-27 11:57:02

标签: android android-sqlite android-room

以下代码未将自动增量ID重置/清除为0

database = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, DatabaseMeta.DB_NAME)
            .build();
database.query("DELETE FROM sqlite_sequence WHERE name = ?", new Object[]{"tableName"});

database.query("REPLACE INTO sqlite_sequence (name, seq) VALUES ('mission', -1)", null);

无论如何要在Android会议室中清除sqlite_sequence吗?

Android房间没有使用“sqlite_sequence”来进行自动增量逻辑我认为,不确定。尝试打印sqlite_sequence条目,找不到我使用的表名(具有自动增量主键)。

3 个答案:

答案 0 :(得分:1)

使用AUTOINCREMENT时用于确定 rowid 的算法,因此在创建/使用 sqlite_sequence 时,使用现有最高中的较高者> rowid 或sqlite_sequence表中的值(seq列)。

因此,如果关联表中存在任何行,那么设置seq列如果不是大于关联表中最高 rowid 的值,则无效。

如果表没有行,那么我认为删除表会导致sqlite_sequence表中的相应行被自动删除。

答案 1 :(得分:1)

尝试使用此代码对我有用

class FeedReaderDbHelper extends SQLiteOpenHelper {
    static final int DATABASE_VERSION = 1;
    static final String DATABASE_NAME = DBConfig.DATABASE_NAME;

    FeedReaderDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onCreate(db);
    }

    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(mainContext.getApplicationContext());
mDbHelper.getWritableDatabase().execSQL("DELETE FROM sqlite_sequence WHERE name='table_name';");

答案 2 :(得分:0)

我将此函数放在RoomDatabase类中:

        companion object {

    fun resetPointer(nonRoomDb: MyRoomDatabase){

      nonRoomDb.openHelper.writableDatabase.execSQL("DELETE FROM sqlite_sequence")

}       
}

因此您可以在代码中的任何地方调用它:

    val database = MyRoomDatabase.getInstance(application)

    MyRoomDatabase.resetPointer(database)