1APP开发期间的数据库改动(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.
数据库升级的话,会删除所有表,然后重新创建。这种方式在开发期间,APP还没有上线之前是可以的。
当APP上线后,我们不能使用这种方式,因为这样会导致已经存在的数据会被删除。
2APP上线后,数据库升级
需要我们写一个类来实现OpenHelper
代码见:http://git.oschina.net/weijianstar/codes/9dkqn1s2jeml6b8tucg5p
- 我们自己实现了
onUpgrade
方法来自定义升级过程。
2.当然升级过程中也要修改DaoMaster.SCHEMA_VERSION
3.当DaoMaster.SCHEMA_VERSION
跟你当前数据库的版本比较后,
会根据你当前数据库的版本,然后进行升级。
4.关键代码onUpgrade
方法,会比较新数据库和旧数据库的版本,然后执行相应的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);
}
}
网友评论