直接添加表字段,不升级会报异常如上图。
1.表字段或减少表字段
2.增加表
如上等情况需要升级数据库
方法如下(以添加表字段为例):
@Database(
entities = [XXInfo::class],
version = 2 // 旧版本为1
)
init {
var migrations = mutableListOf<Migration>()
migrations.add(Migration12(1,2))
var baseBuilder = BaseBuilder(RoomCallback(),migrations)
XXDb.init(baseBuilder)
}
private class Migration12(startVersion: Int, endVersion: Int) : Migration(startVersion, endVersion) { override fun migrate(database: SupportSQLiteDatabase) { LionLog.i(TAG,"Migration12 migrate") database.execSQL("ALTER TABLE XXInfo "+" ADD COLUMN 'total' INTEGER "+" NOT NULL DEFAULT 0"); } }
向XXInfo表中插入 total字段