使用Room库时遇到迁移错误:如何修改列的affinity参数?
Got it, let's figure out how to fix this affinity issue you're hitting with Room migrations.
What's Causing the Mismatch?
First, a key SQLite quirk to note: it doesn't have a native STRING data type. When you use STRING in your ALTER TABLE statement, SQLite automatically assigns it a NUMERIC affinity (which is that affinity='1' you're seeing). But Room expects a TEXT type for Kotlin String properties, which uses TEXT affinity (affinity='2'). That's exactly where your schema mismatch is coming from.
The Simple Fix
All you need to do is swap out STRING for TEXT in your migration SQL statement. Here's the corrected migration code:
database.execSQL("ALTER TABLE values ADD COLUMN serial_number_prefix TEXT DEFAULT null")
Why This Works
- Using
TEXTin the SQL tells SQLite to assign the correct TEXT affinity (value 2) that aligns with what Room expects for yourString?property. - Your data class code is already perfect—Room automatically maps Kotlin
String?properties to TEXT columns, so no changes are needed there.
Quick Verification
After updating the migration, Room will recognize the column's affinity as 2, matching the expected schema, and that migration error should disappear entirely.
内容的提问来源于stack exchange,提问作者Chris

