Android sqlite更新数据库时删除了所有数据

时间:2015-07-26 18:33:34

标签: android database sqlite

我正在尝试在升级应用程序时将数据从旧数据库移动到新数据库版本,但是当我运行新版本的应用程序时,所有数据都消失了,没有数据

这是我的onUpgrade代码:

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            if (oldVersion < newVersion) {
                Log.v("ONUPRGADE", "ITS HEREEEEEEEE");
                db.beginTransaction();
                db.execSQL("ALTER TABLE " + TABLE_NAME + " RENAME TO " + "temp_" + TABLE_NAME + ";");
                db.execSQL("ALTER TABLE atomicid" + " RENAME TO " + "temp_atomicid;");

                String Create_Table = "CREATE TABLE " + TABLE_NAME + " ( " + PRIMARY_KEY + " INTEGER  PRIMARY KEY  AUTOINCREMENT , "
                        + ALARM_NAME + " TEXT NOT NULL , " + ALARM_TIME + " TEXT NOT NULL , " + DAY_OR_NIGHT + " TEXT NOT NULL , "
                        + Tone + " TEXT NOT NULL , " + SUNDAY + " TEXT  , " + MONDEY + " TEXT  , " + TUESDAY
                        + " TEXT  , " + WEDNESDAY + " TEXT  , " + THURSDAY + " TEXT  , "
                        + FRIDAY + " TEXT  , " + SATARDAY + " TEXT , " + repeatWeekly + "  INTEGER  ); ";
                String AtomicIdTable = "CREATE TABLE atomicid(_id INTEGER PRIMARY KEY , alarmid INTEGER ,day TEXT);";
                db.execSQL(Create_Table);
                db.execSQL(AtomicIdTable);

                db.execSQL("INSERT INTO " + TABLE_NAME + " SELECT FROM temp_" + TABLE_NAME + ";");
                db.execSQL("INSERT INTO atomicid" + " SELECT FROM temp_atomicid" + ";");

                db.execSQL("DROP TABLE temp_" + TABLE_NAME + " IF EXISTS;");
                db.execSQL("DROP TABLE temp_atomicid" + " IF EXISTS;");

                db.setTransactionSuccessful();
                ;
                onCreate(db);

            } else {
                Log.v("ONUPRGADE", "ELSEEEEEEEEEEEE");

                db.execSQL("DROP TABLE " + TABLE_NAME + " IF EXISTS;");
                db.execSQL("DROP TABLE atomicid" + " IF EXISTS;");

                db.endTransaction();
                onCreate(db);
            }
        } finally {
            db.endTransaction();
        }

    }

更新 问题是我在build.gradle上用数据库版本更改了应用程序版本,因此每次运行应用程序时都会删除应用程序及其文件lol

1 个答案:

答案 0 :(得分:0)

更改这些行

  db.execSQL("INSERT INTO " + TABLE_NAME + " SELECT FROM temp_" + TABLE_NAME + ";");
  db.execSQL("INSERT INTO atomicid" + " SELECT FROM temp_atomicid" + ";");

  db.execSQL("INSERT INTO " + TABLE_NAME + " SELECT * FROM temp_" + TABLE_NAME + ";");
  db.execSQL("INSERT INTO atomicid" + " SELECT * FROM temp_atomicid" + ";");