Should there be one SQLiteOpenHelper for each table in the database?

北慕城南 提交于 2019-12-18 03:04:37

问题


Is it better to have a single big SQLiteOpenHelper subclass that defines onCreate and onUpgrade methods for every table in the database, or is better to have many SQLiteOpenHelper subclasses, one for each table?

Is there a best practice? Or are both acceptable, but with different good and bad side effects?


回答1:


You should have a single SQLiteOpenHelper class for all the tables. Check this link.




回答2:


Just for the sake of a different approach:

You can always overried on the onOpen(..) method have it called your onCreate(..) . Be sure to use the "CREATE TABLE IF NOT EXISTS..." statement rather than "CREATE TABLE"

    @Override
public void onOpen(SQLiteDatabase db) {
    onCreate(db);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_FRIENDS_TABLE = "CREATE TABLE IF NOT EXISTS ...";
    db.execSQL(CREATE_FRIENDS_TABLE);
}

You do that with every class that extends from SQLiteOpenHelper




回答3:


@TheReader is right. I prefer a single SQLiteOpenHelper for all tables, here is what i do: pass a List of "table creation" sqls to the Constructor of the SQLiteOpenHelper subClass, then in the onCreate function iterate the list to create each table. so my SQLiteOpenHelper subclass looks sth like this:

public ModelReaderDbHelper(Context context, List<String> createSQLs, List<String> deleteSQLs){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.TABLE_CREATION_SQLS = createSQLs;
        this.TABLE_DELETE_SQLS = deleteSQLs;
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        for(String oneCreation : TABLE_CREATION_SQLS){
            sqLiteDatabase.execSQL(oneCreation);
        }
    }

But that comes another problem: after adding a new table, and install the new version of the app with an existing old one installed, the new table won't be created, because the existence of the old database will prevent the onCreate function from being called. So user has to uninstall the app first, and install the app completely. The DATABASE_VERSION helps, it seem android will not execute the onCreate function if and only if the a existin database with the same name and the same DATABASE_VERSION



来源:https://stackoverflow.com/questions/13877701/should-there-be-one-sqliteopenhelper-for-each-table-in-the-database

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