onUpgrade备份表时_id冲突

_id conflict when backing up tables in onUpgrade

我想跨数据库结构变化持久化table数据,所以基本流程如下:

步骤 1 - 4 按预期执行,但在调用 onCreate() 后重新填充它时,我在 primary_table._id 上得到一个唯一约束异常。

在onUpgrade中,我有以下结构:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("create table CustomerTemp as select * from Customer;");

    db.execSQL("insert into CustomerTemp select * from Customer;");

    db.execSQL("drop table if exists Customer;");

    onCreate(db);//create table customer...

    //this line throws Unique Constraint Exception on Customer._id
    db.execSQL("insert into  Customer select * from CustomerTemp ;");

    db.execSQL("drop table if exists CustomerTemp;");

}

我不明白为什么仅在重新填充主 table 时抛出异常,而不是在填充临时 table 时抛出异常。

db.execSQL("create table CustomerTemp as select * from Customer;");

此命令创建 CustomerTemp table,并将所有行复制到其中。

db.execSQL("insert into CustomerTemp select * from Customer;");

此命令再次复制所有行。 CREATE TABLE AS 语句不会重新创建任何约束(例如 PRIMARY KEY 或 UNIQUE),因此重复项不会导致错误。