更新房间迁移行

She*_*ano 3 android database-migration android-room

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

Kha*_*ara 6

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

您可以使用返回Cursor查询方法访问旧数据。Cursor 可用于获取用户 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;")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记更新数据库版本。