【问题标题】:Update rows on room migrations更新房间迁移的行
【发布时间】:2019-08-26 11:53:42
【问题描述】:

是否可以编写迁移来更新某个表的所有先前数据?
我正在为我的房间数据开发加密,如果我可以在迁移后加密所有行会很好

【问题讨论】:

    标签: android database-migration android-room


    【解决方案1】:

    好吧,在定义迁移时,您可以访问SupportSQLiteDatabase,通过它您可以执行 SQL 查询。您可以使用 SQL 查询使用 update 语句更新以前的数据。

    您可以使用返回Cursorquery 方法访问旧数据。 光标可用于获取用户 ID 和密码等信息。 最终的代码可能看起来像这样。

    val MIGRATION_1_2 = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
            val cursor = database.query("SELECT * FROM user")
            while(cursor.moveToNext()) {
                val id = cursor.getColumnIndexOrThrow("_id")
                val password = cursor.getString("password")
                //-- Hash your password --//
                database.execSQL("UPDATE user
                                  SET password = hashedPassword
                                  WHERE _id = id;")
            }
        }
    }
    

    别忘了更新数据库版本。

    【讨论】:

    • 但是我怎样才能先得到行值呢?我需要它,因为我会加密它们
    • @Shermano 你可以使用查询方法。我更新了答案。
    猜你喜欢
    • 2020-10-08
    • 2020-05-17
    • 2019-02-13
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多