开发者

SQLite Database Upgrading

开发者 https://www.devze.com 2023-03-17 03:28 出处:网络
I am a bit confused with the android SQLite database handling. I went through tutorials but I didn\'t get the exact point.

I am a bit confused with the android SQLite database handling. I went through tutorials but I didn't get the exact point.

We can have a database class that extends SQLiteOpenHelper, and can override onCreate() method and create a database.

Upgrading database part is a bit confusing. In the following method, how to handle the verions onUpdate(SQLiteDatabase db,int old Version,int newVerison)

Does it mean that when the first time we create database the version is 1. Then, once modified the version become 2. Then开发者_如何学运维 if we want to modify again old Version = 2, newVerison = 3

[onUpdate(SQLiteDatabase db,int old Version,int newVerison) ]

This method will be execute when we pass the constructor version as in the following code (as 2)

public DatabaseHelper(Context context) {
  super(context, dbName, null,2);
}

I need to know whether when we need to call onUpgrade() method should we pass version as 2 always or we have to increase one every time for the previous version.


Increment your database version every time the schema changes.

You never need to call onUpgrade directly. Android will call it when required when you open the database by comparing the version of the database with the version that your code is specifying as the current version.

You just need to handle the upgrade process in onUpgrade - it might go something like this:

int curVer = oldVersion;
while ( curVer < newVersion ) {
    curVer++;
    switch ( curVer ) {
        case 2: {
            // Upgrade from V1 to V2
            break;
        }
        case 3: {
            // Upgrade from V2 to V3
            break;
        }
        case 4: {
            // Upgrade from V3 to V4
            break;
        }
    }
}

Lets say your newVersion is 4 and oldVersion is 1 - first iteration will increment curVer to 2 and will run the V2 to V3 upgrade code. Second iteration increments curVer to 3 and runs the V2 to V3 upgrade code, final iteration increments curVer to 4 and runs the V3 to V4 upgrade code.

This works for all values of oldVersion that are less than newVersion. and will sequentially upgrade through the intermediate versions if your users are skipping upgrades of the app.


I use this approach to make database schema evolution a bit easier, you might find it useful too.


its totally up to you that how you are going to maintain the version of database. you can change your version after alteration in table structure or after any modification in content. there is no hard and fast rule for maintaining versioning. its depends on the requirement of the project.

0

精彩评论

暂无评论...
验证码 换一张
取 消