Room的数据库升级分为两种:
- 清空数据库中的数据(不建议使用)
private static AppDatabase create(final Context context) {
return Room.databaseBuilder(
context,
AppDatabase.class,
DB_NAME)
//添加fallbackToDestructiveMigration方法
.fallbackToDestructiveMigration()
.build();
- 在原有数据的基础上,添加自己想要的数据
private static AppDatabase create(final Context context) {
return Room.databaseBuilder(
context,
AppDatabase.class,
DB_NAME)
//添加addMigrations方法
.addMigrations(MIGRATION_1_4)
.build();
-
在原有表的基础上添加新的字段
static Migration MIGRATION_1_2 = new Migration(1, 2) { @Override public void migrate(SupportSQLiteDatabase database) { // 为旧表添加新的字段 database.execSQL("ALTER TABLE Student " + " ADD COLUMN sex INTEGER NOT NULL DEFAULT 0"); } }; @Database(entities = {Student.class}, version = 2, exportSchema = false) public abstract class AppDatabase extends RoomDatabase { } -
添加新的表
static Migration MIGRATION_1_4= new Migration(3, 4) { @Override public void migrate(SupportSQLiteDatabase database) { // 添加新的表 database.execSQL("CREATE TABLE IF NOT EXISTS Book (bookName TEXT, studentId TEXT, bookId PRIMARY KEY )"); } }; @Database(entities = {Student.class}, version = 4, exportSchema = false) public abstract class AppDatabase extends RoomDatabase { }
遇见的问题:
android Room 升级 java.lang.IllegalStateException: Migration didn't properly handle
这里是升级数据库遇到的,添加新的字段类似
sex INTEGER NOT NULL DEFAULT 0
一定要有默认值
来源:CSDN
作者:jhonjson
链接:https://blog.csdn.net/github_34402358/article/details/103237940