1APP開發(fā)期間的數(shù)據(jù)庫改動(APP未上線)
直接上DaoMaster
的代碼
/** * WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
注意看第一行注釋:WARNING: Drops all table on Upgrade! Use only during development.
數(shù)據(jù)庫升級的話哀托,會刪除所有表,然后重新創(chuàng)建。這種方式在開發(fā)期間,APP還沒有上線之前是可以的。
當(dāng)APP上線后,我們不能使用這種方式此蜈,因為這樣會導(dǎo)致已經(jīng)存在的數(shù)據(jù)會被刪除。
2APP上線后,數(shù)據(jù)庫升級
需要我們寫一個類來實現(xiàn)OpenHelper
代碼見:http://git.oschina.net/weijianstar/codes/9dkqn1s2jeml6b8tucg5p
- 我們自己實現(xiàn)了
onUpgrade
方法來自定義升級過程。
2.當(dāng)然升級過程中也要修改DaoMaster.SCHEMA_VERSION
3.當(dāng)DaoMaster.SCHEMA_VERSION
跟你當(dāng)前數(shù)據(jù)庫的版本比較后,
會根據(jù)你當(dāng)前數(shù)據(jù)庫的版本腰奋,然后進行升級。
4.關(guān)鍵代碼onUpgrade
方法,會比較新數(shù)據(jù)庫和舊數(shù)據(jù)庫的版本,然后執(zhí)行相應(yīng)的sql升級:
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
LogUtil.w(SQLiteOpenHelper.class.getSimpleName(), "Upgrade from" + oldVersion + "to" + newVersion);
SortedMap<Integer, Migration> migrations = ALL_MIGRATIONS.subMap(oldVersion, newVersion);
executeMigrations(sqLiteDatabase, migrations.keySet());
}
private void executeMigrations(final SQLiteDatabase paramSQLiteDatabase, final Set<Integer> migrationVersions) {
for (final Integer version : migrationVersions) {
ALL_MIGRATIONS.get(version).migrate(paramSQLiteDatabase);
}
}