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?

4

2 に答える 2

3

で試してくださいif not exists

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

そして、いつものように。

于 2012-11-20T09:38:04.710 に答える
1

最初にテーブルが存在するかどうかを確認し、次を使用します。

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();
于 2012-11-20T09:37:09.217 に答える