如果使用SQLiteOpenHelper管理查詢,有一個叫做OnUpgrade方法將調用當用戶升級他的應用程序時,新版本的應用程序的版本代碼大於以前的版本。
一個例子使用:
public static void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(TodoTable.class.getName(), "Upgrading database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
onCreate(database);
}
在這裏,您可以使用oldVersion和NEWVERSION做數據庫的增量更新,如果你不想剛落你的表。您必須確保您增加數據庫版本號。數據庫版本號作爲構造函數參數傳遞給SQLiteOpenHelper。
增量升級的一個例子:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
db.beginTransaction();
boolean success = true;
for (int i = oldVersion ; i < newVersion ; ++i) {
int nextVersion = i + 1;
switch (nextVersion) {
case 2:
success = upgradeToVersion2(db);
break;
// etc. for later versions.
case 3:
success = upgradeToVersion3(db);
break;
}
if (!success) {
break;
}
}
if (success) {
db.setTransactionSuccessful();
}
db.endTransaction();
}
}