我想跨数据库结构变化持久化表数据,所以基本流程如下:
- 创建临时表
- 使用主表中的数据填充临时表
- 删除主表
- onCreate() 被调用
- 用临时表中的数据填充主表
- 删除临时表
步骤 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;");
}
我不明白为什么只在重新填充主表时抛出异常,而不是在填充临时表时抛出异常。
最佳答案
db.execSQL("create table CustomerTemp as select * from Customer;");
此命令创建 CustomerTemp
表,并将所有行复制到其中。
db.execSQL("insert into CustomerTemp select * from Customer;");
此命令再次复制所有行。 CREATE TABLE AS 语句不会重新创建任何约束(例如 PRIMARY KEY 或 UNIQUE),因此重复项不会导致错误。
关于android - onUpgrade备份表时_id冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44750970/