在单独的SQLiteOpenHelper类中的现有数据库中创建新表 [英] Create new table in existing DB in separate SQLiteOpenHelper class

查看:206
本文介绍了在单独的SQLiteOpenHelper类中的现有数据库中创建新表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在已经创建并部署的应用程序中,我使用扩展了SQLiteOpenHelper的单个类文件创建了数据库 MainDB .

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.

现在,我在应用程序中添加了一个全新的模块,该模块还将与DB交互,但具有不同的新表.

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.

现在,我已经在BaseSQLiteOpenHelper类中创建了数据库.

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,

仅在BaseSQLiteOpenHelper类中的onCreate()中创建我的新表(与此相关的问题是在同一个类中提及新表似乎很尴尬,因为该类与我的新表无关).

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).

请提出建议.

谢谢

推荐答案

首先检查该数据库的当前数据库版本

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);
}

并增加数据库版本(DATABASE_VERSION),并在如下所示的Upgrade和oncreate方法中添加新表查询.

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");
    }
}

完成!!!

这篇关于在单独的SQLiteOpenHelper类中的现有数据库中创建新表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆