简体   繁体   中英

Upgrade database on deployed Android app on update

I have an app deployed on play store. I use SQLite database. The app that is on play store have db version 3. Now for the upcoming update I want to add another column to the table in the database, so I am going to increase db version to 4. I have made that logic inside my onUpgrade() method. I am just wondering how you find it, how you get around this kind of situation, for even further updates like the one with db version 5. I just want to get your opinions. Thanks a lot.

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //when deployed to play store version was 3
        //update db table. And increase db version on top

        String queryForDBVersion4 = "ALTER TABLE " + TABLE_NAME + " ADD noteColor TEXT";
//        String queryForDBVersion5;

        switch (newVersion){
            case 4:
                db.execSQL(queryForDBVersion4);
                break;
//            case 5:       //FOR FUTURE USE
//                if(oldVersion==4){db.execSQL(queryForDBVersion5);}
//                else{
//                    db.execSQL(queryForDBVersion4);
//                    db.execSQL(queryForDBVersion5);
//                }
//                break;
//            case 6: SO ON...  
        } 
}

I prefer this way as it is clean and simple:

public void onUpgrade(final SQLiteDatabase db, int oldVersion, int newVersion) {

    if (oldVersion < 2){
    // Upgrade from V1 to V2
    }

    if (oldVersion < 3){
    // Upgrade from V2 to V3
    }

    if (oldVersion < 4){
    // Upgrade from V3 to V4
    }

}

Using this, the database will incrementally upgrade.

Change db version and check column exists in table inside onUpgrade

public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    Cursor cursor = arg0.rawQuery("select * from TABLE_NAME", null);
    int newcolumn = cursor.getColumnIndex("NEWLY_ADDED_COLUMN_NAME");
    if (newcolumn == -1) {
        arg0.execSQL("ALTER TABLE TABLE_NAME ADD COLUMN NEWLY_ADDED_COLUMN_NAMEtext");
    }
}

Here's a nice way to do it.

public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion)
{
    int upgradeTo = oldVersion + 1;
    while (upgradeTo <= newVersion)
    {
        switch (upgradeTo)
        {
            case 5:
                db.execSQL(SQLiteSet.V5_ADD_LAST_CARD);
                db.execSQL(SQLiteCard.V5_ADD_FAILED);
                break;
            case 6:
                db.execSQL(SQLiteSet.V6_ADD_IMPORT_TYPE);
                break;
            case 7:
                db.execSQL(SQLiteSet.V7_ADD_SHORT_FNAME);
                break;
        }
        upgradeTo++;
    }
}

initial post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM