更改数据库版本后如何保留表值?

时间:2018-10-03 05:16:54

标签: android android-sqlite

我正在使用greendao库进行数据库操作。我有些疑问,

  1. 当前,当我在entity之一中添加任何database table时, 必须将我的数据库版本更新到下一个版本。如果我不更新 版本应用程序因某种原因崩溃。真的需要在每次添加或更新表实体时更新数据库版本吗?
  2. 但是,当我更新数据库版本时,所有数据库值都将被清除。如何在更新数据库版本后保持数据库值不变?

请帮助

提前谢谢

1 个答案:

答案 0 :(得分:0)

您必须编写迁移文件以防止擦除数据。

以下是示例代码的外观:

public class DatabaseUpgradeHelper extends DaoMaster.OpenHelper {
    public DatabaseUpgradeHelper(Context context, String name) {
        super(context, name);
    }
    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
        List<Migration> migrations = getMigrations();
        // Only run migrations past the old version
        for (Migration migration : migrations) {
            if (oldVersion < migration.getVersion()) {
                migration.runMigration(db);
            }
        }
    }
    private List<Migration> getMigrations() {
        List<Migration> migrations = new ArrayList<>();
        migrations.add(new MigrationV2());
        migrations.add(new MigrationV3());
        // Sorting just to be safe, in case other people add migrations in the wrong order.
        Comparator<Migration> migrationComparator = new Comparator<Migration>() {
            @Override
            public int compare(Migration m1, Migration m2) {
                return m1.getVersion().compareTo(m2.getVersion());
            }
        };
        Collections.sort(migrations, migrationComparator);
        return migrations;
    }
    private static class MigrationV2 implements Migration {
        @Override
        public Integer getVersion() {
            return 2;
        }
        @Override
        public void runMigration(Database db) {
            //Adding new table
            UserDao.createTable(db, false);
        }
    }
    private static class MigrationV3 implements Migration {
        @Override
        public Integer getVersion() {
            return 3;
        }
        @Override
        public void runMigration(Database db) {
            // Add new column to user table
            db.execSQL("ALTER TABLE " + UserDao.TABLENAME + " ADD COLUMN " + UserDao.Properties.Age.columnName + " INTEGER");
        }
    }
    private interface Migration {
        Integer getVersion();
        void runMigration(Database db);
    }
}