GreenDAO是一款非要流行的android平台上的数据库框架,性能优秀,代码简洁。 
初始化数据库模型代码的时候需要使用java项目生成代码,依赖的jar包已经上传到我的资源里了,下载地址如下:http://download.csdn.net/detail/fancylovejava/8859203

项目开发中用到的就是GreenDAO数据库框架,需要进行数据库版本升级。 
其实数据库版本升级比较麻烦的就是数据的迁移,data migration。

数据库版本升级有很多方法,按不同需求来处理。

本质上是去执行sql语句去创建临时数据表,然后迁移数据,修改临时表名等。

数据版本升级,为了便于维护代码可以先定义一个抽象类

public abstract class AbstractMigratorHelper {
public abstract void onUpgrade(SQLiteDatabase db);
}

然后让自己更新数据库逻辑的类继承这个类

public class DBMigrationHelper6 extends AbstractMigratorHelper {

/* Upgrade from DB schema 6 to schema 7 , version numbers are just examples*/

public void onUpgrade(SQLiteDatabase db) {

    /* Create a temporal table where you will copy all the data from the previous table that you need to modify with a non supported sqlite operation */
db.execSQL("CREATE TABLE " + "'post2' (" + //
"'_id' INTEGER PRIMARY KEY ," + // 0: id
"'POST_ID' INTEGER UNIQUE ," + // 1: postId
"'USER_ID' INTEGER," + // 2: userId
"'VERSION' INTEGER," + // 3: version
"'TYPE' TEXT," + // 4: type
"'MAGAZINE_ID' TEXT NOT NULL ," + // 5: magazineId
"'SERVER_TIMESTAMP' INTEGER," + // 6: serverTimestamp
"'CLIENT_TIMESTAMP' INTEGER," + // 7: clientTimestamp
"'MAGAZINE_REFERENCE' TEXT NOT NULL ," + // 8: magazineReference
"'POST_CONTENT' TEXT);"); // 9: postContent /* Copy the data from one table to the new one */
db.execSQL("INSERT INTO post2 (_id, POST_ID, USER_ID, VERSION, TYPE, MAGAZINE_ID, SERVER_TIMESTAMP, CLIENT_TIMESTAMP, MAGAZINE_REFERENCE, POST_CONTENT)" +
" SELECT _id, POST_ID, USER_ID, VERSION, TYPE, MAGAZINE_ID, SERVER_TIMESTAMP, CLIENT_TIMESTAMP, MAGAZINE_REFERENCE, POST_CONTENT FROM post;"); /* Delete the previous table */
db.execSQL("DROP TABLE post");
/* Rename the just created table to the one that I have just deleted */
db.execSQL("ALTER TABLE post2 RENAME TO post"); /* Add Index/es if you want them */
db.execSQL("CREATE INDEX " + "IDX_post_USER_ID ON post" +
" (USER_ID);");
//Example sql statement
db.execSQL("ALTER TABLE user ADD COLUMN USERNAME TEXT");
}
}

最后在OpenHelper方法里的OnUpgrade方法里面处理,这里方法调用的比较巧妙,借用国外大牛的代码复制下。

public static class UpgradeHelper extends OpenHelper {

    public UpgradeHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
} /**
* Here is where the calls to upgrade are executed
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { /* i represent the version where the user is now and the class named with this number implies that is upgrading from i to i++ schema */
for (int i = oldVersion; i < newVersion; i++) {
try {
/* New instance of the class that migrates from i version to i++ version named DBMigratorHelper{version that the db has on this moment} */
AbstractMigratorHelper migratorHelper = (AbstractMigratorHelper) Class.forName("com.nameofyourpackage.persistence.MigrationHelpers.DBMigrationHelper" + i).newInstance(); if (migratorHelper != null) { /* Upgrade de db */
migratorHelper.onUpgrade(db);
} } catch (ClassNotFoundException | ClassCastException | IllegalAccessException | InstantiationException e) { Log.e(TAG, "Could not migrate from schema from schema: " + i + " to " + i++);
/* If something fail prevent the DB to be updated to future version if the previous version has not been upgraded successfully */
break;
} }
}
}

上面已经做了数据的迁移,国外有个大牛封装的代码摘抄下来:

/**
* Created by pokawa on 18/05/15.
*/
public class MigrationHelper { private static final String CONVERSION_CLASS_NOT_FOUND_EXCEPTION = "MIGRATION HELPER - CLASS DOESN'T MATCH WITH THE CURRENT PARAMETERS";
private static MigrationHelper instance; public static MigrationHelper getInstance() {
if(instance == null) {
instance = new MigrationHelper();
}
return instance;
} public void migrate(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
generateTempTables(db, daoClasses);
DaoMaster.dropAllTables(db, true);
DaoMaster.createAllTables(db, false);
restoreData(db, daoClasses);
} private void generateTempTables(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for(int i = ; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]); String divider = "";
String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
ArrayList<String> properties = new ArrayList<>(); StringBuilder createTableStringBuilder = new StringBuilder(); createTableStringBuilder.append("CREATE TABLE ").append(tempTableName).append(" ("); for(int j = ; j < daoConfig.properties.length; j++) {
String columnName = daoConfig.properties[j].columnName; if(getColumns(db, tableName).contains(columnName)) {
properties.add(columnName); String type = null; try {
type = getTypeByClass(daoConfig.properties[j].type);
} catch (Exception exception) {
Crashlytics.logException(exception);
} createTableStringBuilder.append(divider).append(columnName).append(" ").append(type); if(daoConfig.properties[j].primaryKey) {
createTableStringBuilder.append(" PRIMARY KEY");
} divider = ",";
}
}
createTableStringBuilder.append(");"); db.execSQL(createTableStringBuilder.toString()); StringBuilder insertTableStringBuilder = new StringBuilder(); insertTableStringBuilder.append("INSERT INTO ").append(tempTableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(" FROM ").append(tableName).append(";"); db.execSQL(insertTableStringBuilder.toString());
}
} private void restoreData(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for(int i = ; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]); String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
ArrayList<String> properties = new ArrayList(); for (int j = ; j < daoConfig.properties.length; j++) {
String columnName = daoConfig.properties[j].columnName; if(getColumns(db, tempTableName).contains(columnName)) {
properties.add(columnName);
}
} StringBuilder insertTableStringBuilder = new StringBuilder(); insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";"); StringBuilder dropTableStringBuilder = new StringBuilder(); dropTableStringBuilder.append("DROP TABLE ").append(tempTableName); db.execSQL(insertTableStringBuilder.toString());
db.execSQL(dropTableStringBuilder.toString());
}
} private String getTypeByClass(Class<?> type) throws Exception {
if(type.equals(String.class)) {
return "TEXT";
}
if(type.equals(Long.class) || type.equals(Integer.class) || type.equals(long.class)) {
return "INTEGER";
}
if(type.equals(Boolean.class)) {
return "BOOLEAN";
} Exception exception = new Exception(CONVERSION_CLASS_NOT_FOUND_EXCEPTION.concat(" - Class: ").concat(type.toString()));
Crashlytics.logException(exception);
throw exception;
} private static List<String> getColumns(SQLiteDatabase db, String tableName) {
List<String> columns = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 1", null);
if (cursor != null) {
columns = new ArrayList<>(Arrays.asList(cursor.getColumnNames()));
}
} catch (Exception e) {
Log.v(tableName, e.getMessage(), e);
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
}
return columns;
}
}

然后在OnUpgrade方法里面去调用

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by migrating all tables data"); MigrationHelper.getInstance().migrate(db,
UserDao.class,
ItemDao.class);
}

上面代码全是干货,记录下来以备不时之需!

GreenDAO数据库版本升级

GreenDAO数据库版本升级的更多相关文章

  1. GreenDao 数据库:使用Raw文件夹下的数据库文件以及数据库升级

    一.使用Raw文件夹下的数据库文件 在使用GreenDao框架时,数据库和数据表都是根据生成的框架代码来自动创建的,从生成的DaoMaster中的OpenHelper类可以看出: public sta ...

  2. GreenDao数据库的升级

    应用使用了GreenDao数据库,在版本升级的时候需要更改dao的字段,新增.修改.删除字段操作,如果直接删除原来的表的话那用户原来的一些数据就没有了,所以在更新数据库的时候需要做一次封装,把原来的数 ...

  3. sqlite升级--浅谈Android数据库版本升级及数据的迁移

    Android开发涉及到的数据库采用的是轻量级的SQLite3,而在实际开发中,在存储一些简单的数据,使用SharedPreferences就足够了,只有在存储数据结构稍微复杂的时候,才会使用数据库来 ...

  4. Android SQLite数据库版本升级原理解析

    Android使用SQLite数据库保存数据,那数据库版本升级是怎么回事呢,这里说一下. 一.软件v1.0 安装v1.0,假设v1.0版本只有一个account表,这时走继承SQLiteOpenHel ...

  5. 记录一下寄几个儿的greendao数据库升级,可以说是非常菜鸡了嗯

    之前使用的greendao数据库存储服务器所有的历史推送消息,但是后来消息需要加几个新的字段 举个栗子,比如要新增红色框住的字段到数据库中: 本仙女作为一只思想成熟的菜鸡,当然是加了字段就赶紧重新往里 ...

  6. 转载:Android SQLite数据库版本升级原理解析

    Android使用SQLite数据库保存数据,那数据库版本升级是怎么回事呢,这里说一下. 一.软件v1.0 安装v1.0,假设v1.0版本只有一个account表,这时走继承SQLiteOpenHel ...

  7. 使用SQLiteOpenHelper的onUpgrade实现数据库版本升级

    Andoird的SQLiteOpenHelper类中有一个onUpgrade方法.帮助文档中只是说当数据库升级时该方法被触发.经过实践,解决了我一连串的疑问: 1. 帮助文档里说的"数据库升 ...

  8. GreenDao数据库框架的配置与增删改查

    并非原创,原创地址http://blog.csdn.net/njweiyukun/article/details/51893092 配置-------------------------------- ...

  9. GreenDao数据库结构升级

    1.先用GreenDao工具类编写自动创建代码,按照升级后的最新数据库结构来编写 2.GreenDao工具自动生成的代码覆盖到项目里去 3.在项目里找到对应的自动生成的数据库DaoMaster类 在D ...

随机推荐

  1. 我写的一个 Qt 显示图片的控件

    Qt 中没有专门显示图片的控件.通常我们会使用QLabel来显示图片.可是QLabel 显示图片的能力还是有点弱.比方不支持图像的缩放一类的功能.使用起来不是非常方便. 因此我就自己写了个简单的类. ...

  2. D - 二叉树遍历(推荐)

    二叉树遍历问题 Description   Tree Recovery Little Valentine liked playing with binary trees very much. Her ...

  3. 【Linux命令】命令行查找文件并进行操作

    查找: #找./下的所有txt文件,输出个数 find ./ -name "*.txt" | wc -l #查找并删除 find ./ -name "*.txt" ...

  4. Minimum Window Substring @LeetCode

    不好做的一道题,发现String Algorithm可以出很多很难的题,特别是多指针,DP,数学推导的题.参考了许多资料: http://leetcode.com/2010/11/finding-mi ...

  5. Android:AysncTask异步加载

    以下是链接: http://blog.csdn.net/abc5382334/article/details/17097633 http://keeponmoving.iteye.com/blog/1 ...

  6. Python 执行字符串表达式函数(eval exec execfile)

    eval:计算字符串中的表达式 exec:执行字符串中的语句 execfile:用来执行一个文件 在python 2中exec是语句,在python3中exec变为函数,后面要跟括号.在python3 ...

  7. mongodb进阶一之高级查询

    上篇文章我们讲了mongodb的crud基本操作 http://blog.csdn.net/stronglyh/article/details/46812579 这篇我们来说说mongodb的进阶-- ...

  8. 【原创】Android 系统稳定性 - ANR(二)

    文章都为原创,转载请注明出处,未经允许而盗用者追究法律责任. 很久之前写的了,留着有点浪费,共享之.编写者:李文栋P.S. OpenOffice粘贴过来后格式有些混乱. 1.2 如何分析ANR问题 引 ...

  9. android4.4组件分析--service组件

    6       Service 6.1            service介绍 6.1.1.            基本介绍 Service是Android四大组件之中的一个(其余的是activit ...

  10. Android创建与读取Excel

    主流的操作Excel的有两种方法,一种是通过poi包,另一种是通过jxl包.这里我主要讲解通过jxl包来读写Excel. 首先需要导入一个jxl.jar包. 下载地址:http://www.andyk ...