【问题标题】:Room Migration didn't properly handle房间迁移没有正确处理
【发布时间】:2019-04-23 19:04:24
【问题描述】:

得到以下异常:

预期:

TableInfo{name='chat_table', columns={message=Column{name='message', type='TEXT',affinity='2',notNull=false,primaryKeyPosition=0}, messageStatus=Column{name='messageStatus', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER',affinity='3',notNull=true,primaryKeyPosition=1}}, foreignKeys=[], 索引=[]}

找到:

TableInfo{name='chat_table', columns={messageStatus=Column{name='messageStatus', type='TEXT', 亲和力='2',notNull=false,primaryKeyPosition=0}, id=列{name='id',type='INTEGER',affinity='3',notNull=false, primaryKeyPosition=1}, message=Column{name='message', type='TEXT', 亲和力='2',notNull=false,primaryKeyPosition=0}},foreignKeys=[], 指数=[]}

任何人都可以提出这里的问题吗?我只是将表列值复制到另一个表。然后删除第一个表,然后将新表重命名为旧名称。

 1. database.execSQL("CREATE TABLE chat_table_new (id INTEGER,
        messageStatus TEXT, message TEXT, PRIMARY KEY(id))")
 2. database.execSQL("INSERT INTO chat_table_new SELECT * FROM
        chat_table") 
 3. database.execSQL("DROP TABLE chat_table") 
 4. database.execSQL("ALTER TABLE chat_table_new RENAME TO chat_table")

【问题讨论】:

    标签: android android-room


    【解决方案1】:

    试试这个方法..

    @Database(entities = {Student.class, BookIssue.class},version = 1)
    public abstract class StudentDatabase extends RoomDatabase {
    private static StudentDatabase studentDatabase;
    public static StudentDatabase getStudentDatabase(Context context)
    {
        if (studentDatabase==null)
        {
            studentDatabase= Room.databaseBuilder(context.getApplicationContext(),StudentDatabase.class,"student-database").addMigrations(StudentDatabase.MIGRATION_1_2).build();
    
        }
    
        return studentDatabase;
    }
    
    public abstract StudentDao studentDao();
    public abstract BookDao bookDao();
    
    public static final Migration MIGRATION_1_2 =new Migration(1,2) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            database.execSQL("alter table Student "+"add column pf String");
        }
    };
    }
    

    更多了解请参考此链接 https://medium.com/androiddevelopers/understanding-migrations-with-room-f01e04b07929

    【讨论】:

    • 感谢您的帮助。但是,ALTER 表用于向 DB 添加列或重命名表名。但是,要删除列或重命名列名,我们必须遵循上述方法。对此有什么想法吗?
    • 可以对数据库操作进行MySql全部查询。首先从mysql读取所有数据库操作,然后对room db执行操作。
    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 2018-03-27
    • 2019-04-13
    • 2020-02-17
    • 1970-01-01
    • 2021-01-21
    相关资源
    最近更新 更多