CoolStraw
CoolStraw

Reputation: 5390

Phonegap app SQLite db initial set up

What are the best practices to build an app's database schema on first execution?

In other words what I am trying to find out is:

SQLite does not support comma separated queries to be executed as a one statement batch. How to replace that so that the code stays future proof? (I don't see myself putting all the create statements in tx.executeSQL("") chained sequentially it would turn my code into a horrible piece of cr*p).

Upvotes: 2

Views: 945

Answers (1)

Ushal Naidoo
Ushal Naidoo

Reputation: 2744

What I do, in native code as well as in Sencha/Phonegap is to use a DatabaseHelper Class that I refer to. In that class you can see the version of the Database with :

public DataBaseHelper(Context context) {
    super(context, DB_NAME, null, 2);
    this.myContext = context;
}

public void createDataBase() throws IOException {
    boolean dbExist = checkDataBase();
    if (dbExist) {
        // do nothing - database already exist
         openDataBase();
            int cVersion = myDataBase.getVersion();
            if(cVersion != 2){
                onUpgrade(myDataBase, myDataBase.getVersion(), 2);}
            close();
    } ....}

    @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        this.getReadableDatabase();
        try{
        db.execSQL("ADD SQL QUERY HERE TO ADD TABLE");
}
        catch(Exception e){}
    }


private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
            } catch (SQLiteException e) {
            // database does't exist yet.
            }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

Although this is tedious it keeps your database future proof and the query is called at run time. This covers both your needs.

I hope this helps :)

Upvotes: 2

Related Questions