GreenDao 数据库升级

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

  1. 我们自己实现了onUpgrade方法来自定义升级过程。

        2.当然升级过程中也要修改DaoMaster.SCHEMA_VERSION

        3.当DaoMaster.SCHEMA_VERSION 跟你当前数据库的版本比较后,

        会根据你当前数据库的版本,然后进行升级。

       4.关键代码onUpgrade方法,会比较新数据库和旧数据库的版本,然后执行相应的sql升级:


  SQLiteOpenHelper.java
克隆地址 一键复制 原始数据 历史
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
      
      
      
      
/**
* Created by weijianxing on 9/22/15.
*/
public class SQLiteOpenHelper extends DaoMaster . OpenHelper {
private static final String DB_NAME = "test.db" ;
private static final SortedMap < Integer , Migration > ALL_MIGRATIONS = new TreeMap <>();
static {
ALL_MIGRATIONS . put ( 1 , new V1Migration ());
ALL_MIGRATIONS . put ( 2 , new V2Migration ());
ALL_MIGRATIONS . put ( 3 , new V3Migration ());
}
public SQLiteOpenHelper ( Context context , SQLiteDatabase . CursorFactory factory ) {
super ( context , DB_NAME , factory );
}
@Override
public void onCreate ( SQLiteDatabase db ) {
super . onCreate ( db );
executeMigrations ( db , ALL_MIGRATIONS . keySet ());
}
@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 );
}
}
}
/**
* Created by weijianxing on 9/22/15.
*/
public interface Migration {
void migrate ( SQLiteDatabase db );
}
/**
* Created by weijianxing on 9/22/15.
*/
public class V1Migration implements Migration {
@Override
public void migrate ( SQLiteDatabase db ) {
db . execSQL ( "ALTER TABLE NOTE ADD COLUMN test" );
}
}



你可能感兴趣的:(GreenDao 数据库升级)