ORMLite update of the database

前端 未结 4 717
陌清茗
陌清茗 2020-12-09 04:18

I\'m actually developing an app which is using ORMLite library (which is wonderful btw) but I\'m a beginner using it.

I have a question about the update of the datab

4条回答
  •  既然无缘
    2020-12-09 04:53

    When this person is doing an update of the app, how can I just update the database with my new entries and keep the old ones inside it.

    The idea is to use the version number that is passed to the onUpgrade(...) method. With ORMLite, the OrmLiteSqliteOpenHelper.onUpgrade(...) method takes an oldVersion and newVersion number. You then can write conversion code into your application that is able to convert the data from the old format and update the schema.

    For more information, see the ORMLite docs on upgrading your schema.

    To quote, you could do something like the following:

    if (oldVersion < 2) {
      // we added the age column in version 2
      dao.executeRaw("ALTER TABLE `account` ADD COLUMN age INTEGER;");
    }
    if (oldVersion < 3) {
      // we added the weight column in version 3
      dao.executeRaw("ALTER TABLE `account` ADD COLUMN weight INTEGER;");
    }
    

    If you have existing data that you need to convert then you should do the conversions in SQL if possible.

    Another alternative would be to have an Account entity and an OldAccount entity that point to the same table-name. Then you can read in OldAccount entities using the oldAccountDao, convert them to Account entities, and then update them using the accountDao back to the same table. You need to be careful about object caches here.

提交回复
热议问题