Create new table in existing DB in separate SQLiteOpenHelper class

倖福魔咒の 提交于 2019-12-11 16:43:17

问题


In my already created and deployed application, I've created a database MainDB, using a single class file which extended SQLiteOpenHelper, viz.

public class BaseSQLiteOpenHelper extends SQLiteOpenHelper {

    private final static String DATABASE_NAME = "MainDB";
    ....
    ....
}

Issue is I've tied this class, too much to a particular functionality.

Now I'm adding a totally new module in application, which will also interact with DB, but with different new tables.

Issue is I can't use the same class, as it is conflicting in more than one way. And even if I redesign the code, it will only add complexity from functional/understanding point of view.

So, I've decided to use same DB, but different tables.

Now I've already created DB in BaseSQLiteOpenHelper class.

So, how can I create new tables in seprate class using same DB?

One approach is to use separate Database as well, Or,

Create my new table in onCreate() in BaseSQLiteOpenHelper class only (issue with this is mentioning new table in same class seems awkward, as this class has nothing to do with my new table).

Please suggest.

Thank You


回答1:


First check the current database version for this database

private final static String DATABASE_NAME = "MainDB";
private static final int DATABASE_VERSION = 1;

public BaseSQLiteOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

and increment the database version(DATABASE_VERSION), and add your new table query in on Upgrade and oncreate method like below.

@Override
public void onCreate(SQLiteDatabase db) {
      db.execSQL("old query no need to change");
      db.execSQL("Create your new table here");
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    if (oldVersion < 2) {
       db.execSQL("Create your new table here as well this for update the old DB");
    }
}

Done!!!



来源:https://stackoverflow.com/questions/24632023/create-new-table-in-existing-db-in-separate-sqliteopenhelper-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!