WenChao
WenChao

Reputation: 3665

What is the correct approach to upgrade Database in Android

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 old tables
  3. create new tables and insert old data

Is there a simplified version or there is a better way? Thanks!

Upvotes: 1

Views: 142

Answers (1)

Dhaval Parmar
Dhaval Parmar

Reputation: 18978

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.

Upvotes: 3

Related Questions