【问题标题】:Room Android - How to handle database version upgradeRoom Android - 如何处理数据库版本升级
【发布时间】:2018-01-11 10:19:25
【问题描述】:

我正在阅读有关 Android 架构组件 Room 的内容,并想知道 Room 中是否有任何与 SQLiteOpenHelper 方法中的 onUpgrade 等效的东西可用。

@Override
 public void onUpgrade(final SQLiteDatabase database, final int oldVersion, final int newVersion) {}

【问题讨论】:

标签: android android-room android-architecture-components


【解决方案1】:

你可以使用https://developer.android.com/training/data-storage/room/migrating-db-versions.html

 Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
            .addMigrations(MIGRATION_1_2,MIGRATION_1_3, MIGRATION_2_3).build();

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, "
                    + "`name` TEXT, PRIMARY KEY(`id`))");
        }
    };

    static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE Book "
                    + " ADD COLUMN pub_year INTEGER");
        }
    };

   static final Migration MIGRATION_1_3 = new Migration(1, 3) {
            @Override
            public void migrate(SupportSQLiteDatabase database) {
                database.execSQL("ALTER TABLE Book "
                        + " ADD COLUMN pub_year INTEGER");
            }
        };

【讨论】:

  • 如果用户直接从 1 转到 3 将如何处理
  • @ManishButola 我已经更新了答案,请检查
  • 我认为我们不需要明确处理 1 到 3,因为如果用户从 1 到 3,1 到 2 和 2 到 3 将处理所有事情
【解决方案2】:

在 assets 文件夹中使用以下库和您自己的 sqlite 文件,这样就没有用于创建表的样板代码

编译'com.readystatesoftware.sqliteasset:sqliteassethelper:+'

【讨论】:

    猜你喜欢
    • 2011-07-19
    • 2021-01-06
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    • 1970-01-01
    • 2011-12-29
    相关资源
    最近更新 更多