简体   繁体   English

Android 从版本 2 到 4 的房间迁移?

[英]Android Room Migration from version 2 - 4?

I'm trying to migrate a Room database from versions 2 and 3 to 4 like so:我正在尝试将 Room 数据库从版本 2 和 3 迁移到版本 4,如下所示:

private static final Migration MIGRATION_2_4 = new Migration(2, 4) {
    @Override
    public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {

        database.execSQL(
                "ALTER TABLE 'market_data' ADD COLUMN 'watch_list_boolean' TEXT NOT NULL DEFAULT '0'");

        database.execSQL("DROP TABLE 'developer_data'");
    }
};

but it's not working, what is wrong here?但它不起作用,这里有什么问题?

The problem, most likely (post your stack trace to help future readers), is that your DB won't be able to perform migrations 2->3 and 3->4问题很可能(发布您的堆栈跟踪以帮助未来的读者)是您的数据库将无法执行迁移 2->3 和 3->4

So, your code will only work if your db is upgraded from 2 directly to 4 and will throw an exception (that indicates what migration is missing) if db is upgraded from 2 to 3 or from 3 to 4.因此,只有当您的数据库从 2 直接升级到 4 时,您的代码才会起作用,并且如果数据库从 2 升级到 3 或从 3 升级到 4,则会抛出异常(表明缺少什么迁移)。

Best practice is to create separate migrations - 2 to 3, and 3 to 4.最佳做法是创建单独的迁移 - 2 到 3,以及 3 到 4。

Room will know to execute the correct migrations and in the right order (2->3 or 3->4 or 2->3->4): Room 将知道以正确的顺序执行正确的迁移(2->3 或 3->4 或 2->3->4):

private static final Migration MIGRATION_2_3 = new Migration(2, 3) {
    @Override
    public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
        database.execSQL(
                "ALTER TABLE 'market_data' ADD COLUMN 'watch_list_boolean' TEXT NOT NULL DEFAULT '0'");
    }
};

private static final Migration MIGRATION_3_4 = new Migration(3, 4) {
    @Override
    public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
        database.execSQL("DROP TABLE 'developer_data'");
    }
};

Don't forget to update DB version:)不要忘记更新数据库版本:)

With all due respect, you are taking a conservative approach.恕我直言,您正在采取保守的方法。

Since the Room database uses Gradle to set its version number, it's very easy to change it.由于 Room 数据库使用 Gradle 设置其版本号,因此更改它非常容易。

So, instead of relying on the tools of Gradle and SQLiteDatabase to do this job for you, use the in-memory version of your database and just create the column using plain SQL.因此,不要依赖 Gradle 和 SQLiteDatabase 的工具来为您完成这项工作,而是使用数据库的内存版本,并使用普通的 SQL 创建列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM