What is the correct approach to upgrade Database in Android

前端 未结 1 347
慢半拍i
慢半拍i 2021-01-16 06:59

If I want to keep some of the old data and migrate to a new version of database , what is the correct steps in onUpgrade method?

  1. retain old data
  2. drop
相关标签:
1条回答
  • 2021-01-16 07:15

    upgrade database:

    add new fields in table

    do below steps in onUpgrade

    1. copy old data in temp table

    2. create new table with new fields

    3. again copy data from temp to new table

    4. drop temp table

    also create new table in onCreate for new users

    sample code for on upgrade

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                if (oldVersion < newVersion) {
                    if (oldVersion == 3) {
                        /**
                         * code is upgrade privious version to letest version
                         * */
                        db.beginTransaction();
                        db.execSQL("ALTER TABLE " + TableConstants.TABLE_Mst.getTableName()
                    + " RENAME TO " + TableConstants.TABLE_Mst.getTableName() + "_Obsolete");
            db.execSQL(TABLE_CREATE_query_Mst);
            db.execSQL("INSERT INTO " + TableConstants.TABLE_Mst.getTableName() + "("
                    + "f1, f2, f3) "
                    + " SELECT f1, f2, f3 FROM " + TableConstants.TABLE_Mst.getTableName() + "_Obsolete");
            db.execSQL("DROP TABLE IF EXISTS "
                    + TableConstants.TABLE_Mst.getTableName() + "_Obsolete");
                        db.setTransactionSuccessful();
                        db.endTransaction();
                        db.setVersion(newVersion);
    
                    }
                    }
                    }
    

    add new table in database

    do below steps

    in onUpgrade 1. create new table

    in onCreate 1. create new table

    Note: manage your database version, same for next version, check with older version its work or not.

    0 讨论(0)
提交回复
热议问题