Android强制数据库从0更新为<value>版本

时间:2016-02-15 13:20:16

标签: android sqlite

我有一个班级

public class DbHelper extends SQLiteOpenHelper {

    private static DbHelper mDbHelper = null;
    private final static String TAG = DbHelper.class.getClass().getSimpleName();

    public DbHelper(Context context) {
        super(context, DBManifest.DB_NAME, null, DBManifest.DB_VERSION);
    }

    public static DbHelper getInstance() {
        if (mDbHelper == null)
            mDbHelper = new DbHelper(CommonApplication.mainContext);

        return mDbHelper;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "onCreate called. Current db version = " + db.getVersion());
        for (String query : DBManifest.CREATE_TABLE_QUERY_LIST)
            db.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d(TAG, "onUpgrade called from " + oldVersion + " to " + newVersion + " version.");
        executeMigration(db, oldVersion);
    }


 private void executeMigration(SQLiteDatabase db, int oldVersion) {
        switch (oldVersion) {
            case 0:
            case 1:
            case 2:
                upgradeV2(db);
            case 3:
                upgradeV3(db);
            case 4:
                upgradeV4(db);
            case 5:
                upgradeV5(db);
            case 6:
                upgradeV6(db);
                break;
        }
        db.setVersion(DBManifest.DB_VERSION);
    }

  // migration methods
  // ...
}

我的问题是,当我第一次安装应用程序时,我需要强制将数据库更新为6版本。有可能,怎么做? 上面的代码不起作用。数据库版本保持为0。

1 个答案:

答案 0 :(得分:0)

仅在首次安装应用程序或数据库不存在时才调用

SqliteOpenHelper的onCreate()方法。如果DB_VERSION中有更改,则调用onUpgrade()方法,但是您尝试在数据库甚至存在之前更新数据库,这是不可能的。如果你想更新数据库上的db_version,你可以在手机中拥有数据库之后再做。我希望这对你有所帮助。谢谢你