项目开发中用到的就是GreenDAO数据库框架,需要进行数据库版本升级。
其实数据库版本升级比较麻烦的就是数据的迁移,data migration。
数据库版本升级有很多方法,按不同需求来处理。
本质上是去执行sql语句去创建临时数据表,然后迁移数据,修改临时表名等。
数据版本升级,为了便于维护代码可以先定义一个抽象类
public abstract class AbstractMigratorHelper {
public abstract void onUpgrade(SQLiteDatabase db);
}1234
然后让自己更新数据库逻辑的类继承这个类
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