android - onUpgrade备份表时_id冲突

标签 android sqlite android-database

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

  • 创建临时表
  • 使用主表中的数据填充临时表
  • 删除主表
  • 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/

相关文章:

android - 在 Windows 8 64 位上安装 Nexus 4(带 KitKat)的 USB 驱动程序 - "no compatible software driver"

mysql - 在单个查询中选择许多项目,这些项目本身有很多项目?

php - 使用数据库决策为在线游戏创建大厅的挑战

android - 如何根据日期和时间android每半小时重置一次计数?

android - 房间迁移-如何向现有表添加新的 NON-NULL 和 String 类型的列

javascript - 为什么此代码在 Android 上需要视口(viewport)元标记?

android - 我是否必须创建一个新 Activity 才能使用设置 fragment ?

android - 警告 : Dangling Javadoc comment

date - 格式化日期,如中日期SQLite

android - 插入的行 ID 大于表中的所有条目