当表的结构发生变化时处理方法:
下面方法共同点就是版本号+1
最简单的方法就是在数据库创建时,执行破坏式的迁移
.fallbackToDestructiveMigration()//破坏式迁移
INSTANCE= Room.databaseBuilder(context.getApplicationContext(),WordDatabase.class,"word database")
.fallbackToDestructiveMigration()//破坏式迁移
.build();
这样带来的后果就是数据都会被删除。
还有一种方式式保留数据增加表列的方式:
.addMigrations(XXXXXX)
例子:
当我们bean类添加新的成员变量:
@ColumnInfo(name="bar_data")
private boolean bar;
INSTANCE= Room.databaseBuilder(context.getApplicationContext(),WordDatabase.class,"word database")
.addMigrations(MIGRATION)
.build();
static final Migration MIGRATION=new Migration(2,3) {//从版本2到版本3
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("Alter table word add column bar_data INTEGER not null default 1");
}
};
如果是表列减少时,需要在保存数据的情况下。在sqlite中只能创建新的表进行迁移,保留需要的表列。
static final Migration MIGRATION_3_4=new Migration(3,4) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("Create table word_temp(id Integer primary key not null,english_word TEXT,chinese_meaning TEXT)");
database.execSQL("Insert into word_temp(id,english_word,chinese_meaning) select id,english_word,chinese_meaning from word");
database.execSQL("drop table word");
database.execSQL("Alter table word_temp rename to word");
}
};