升级生产Android应用程序的SQLite数据库,这是正确的吗?

Aut*_*M8R 4 database sqlite android upgrade

正如标题所说,我有一个生产Android应用程序,安装量约为1000.我不得不在SQLite中进行数据库更改,到目前为止,SQLite DB的版本已设置为版本"1".

希望我在注释中充分解释下面的代码,这段代码驻留在我的SQLiteOpenHelper类中,因此onUpgrade方法是Class的一部分:

// Provides an upgrade path for the DB when the apps version is updated.
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // First version of the DB was 1. Logic: each if statement will
        // alter the DB cumulatively based on the version code. So, if the
        // newVersion was version 3, there would be two if statements, one
        // for oldVersion 1 and one for oldVersion 2. oldVersion 2 will
        // contain the logic for upgrading from version 2 to 3, while
        // oldVersion 1 will contain a combination of alter statements
        // allowing the database to upgrade from version 1 directly to
        // version 3.
        if (oldVersion == 1) {
            db.execSQL("ALTER TABLE plans ADD COLUMN " + App.CURRENCYCODE
                    + " TEXT");
            Locale locale = Locale.getDefault();
            ContentValues content_values = new ContentValues();
            content_values.put(App.CURRENCYCODE, locale.toString());

            db.update(App.DBPLANS, content_values, App.ID + " > ?", new String[] {
                    "0"
            });
        }

        if (oldVersion == 2) {
            // Placeholder for next database upgrade instructions.
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果这里有任何陷阱,请告诉我.到目前为止,它测试得很好,虽然我非常担心搞乱我的第一次数据库升级.我有1000个左右的用户,我不想失去他们.

再次感谢!

mah*_*mah 7

当我需要像这样更新数据库时,我通常使用switch语句来执行此操作,其中案例会相互渗透,例如:

switch (oldVersion) {
    case 1:
        // update to version 2
        // do _not_ break; -- fall through!
    case 2:
        // update to version 3
        // again, do not break;
    case 3:
        // you're already up to date
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,当您继续更改数据库时,最终不会在多个if语句中重复更新语句,并且添加数据库更新只需要添加新的case语句,而不是更新多个代码块.

有时会出现例外情况,例如在一个版本中添加了一列但在将来删除了一列,因此您需要注意.