我正在尝试使用SQLite DB创建一个简单的Contacts应用程序。
我创建了自己的DBHelper类:
public class DBHelper {
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_MOBILE = "mobile";
public static final String KEY_HOME = "home";
public static final String KEY_ROW_ID = "_id";
public static final String PROJECTION[] = {
KEY_ROW_ID,
KEY_NAME,
KEY_ADDRESS,
KEY_MOBILE,
KEY_HOME
};
/* The table and database names */
private static final String TABLE_NAME = "mycontacts";
private static final String DATABASE_NAME = "contactDB";
/*SQL code for creating the table*/
private static final String TABLE_CREATE=
"create table "+ TABLE_NAME + "("+ KEY_ROW_ID
+" integer primary key autoincrement,"+
KEY_NAME +" text not null,"+
KEY_ADDRESS + " text not null,"+
KEY_MOBILE + " text,"+
KEY_HOME + " text)";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public DBHelper(Context ctx){
db = ctx.openOrCreateDatabase(DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.execSQL(TABLE_CREATE);
}
...
`enter code here`}
在类的构造函数中,正如您所看到的,我创建/打开数据库,之后我对其进行CREATE_TABLE
查询以创建mycontacts
表。
当我运行应用程序时(在Android Studio的模拟器上),我收到以下运行时错误:
Caused by: android.database.sqlite.SQLiteException: table mycontacts already exists (code 1): , while compiling: create table mycontacts(_id integer primary key autoincrement,name text not null,address text not null,mobile text,home text)
它表示已经创建了表,尽管我在创建db之后立即创建了创建查询。怎么可能?
答案 0 :(得分:0)
将其写为“如果不存在则创建表格”
private static final String TABLE_CREATE=
"create table if not exists"+ TABLE_NAME + "("+ KEY_ROW_ID
+" integer primary key autoincrement,"+
KEY_NAME +" text not null,"+
KEY_ADDRESS + " text not null,"+
KEY_MOBILE + " text,"+
KEY_HOME + " text)";