0
db = openOrCreateDatabase("tompomodoros.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE mytable (_id INTEGER PRIMARY KEY AUTOINCREMENT, mydate VARCHAR, mydata SMALLINT)");

I use above code to create db and its table "mytable". But for the second time I run it, the phone goes to dead. I guess that is because I create the table again but it already exists there. So my question is how to create the table for the first time and open it for the rest times?

1

2 Answers 2

3

Try with if not exists:

db.execSQL("CREATE TABLE if not exists mytable (_id INTEGER PRIMARY KEY AUTOINCREMENT, mydate VARCHAR, mydata SMALLINT)");

and then us it as usual.

Sign up to request clarification or add additional context in comments.

Comments

1

First check if the table exists, use the following:

Cursor cursor = db.rawQuery("SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name = 'mytable'", null);
if(cursor == null || cursor.getCount() == 0) { //table does not exist
        //create the Db attachments table
        db.execSQL("CREATE TABLE mytable (_id INTEGER PRIMARY KEY AUTOINCREMENT, mydate VARCHAR, mydata SMALLINT)");
}
cursor.close();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.