數據庫處理器代碼:使用SQLiteOpenHelper創建多個表可能會導致錯誤?
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydb";
// 1st table --------------------------------------
private static final String TABLE_MODULE = "module";
// Module table columns
private static final String KEY_MODULE_CODE = "code";
private static final String KEY_MODULE_TITLE = "title";
private static final String KEY_MODULE_SEMESTER = "semester";
private static final String KEY_MODULE_TIMETABLE= "timetable";
// 2nd table --------------------------------------
private static final String TABLE_URIS = "applicationURLs";
// Module table columns
private static final String KEY_SERVER_URI = "serverURI";
private static final String KEY_NEWS_URI = "newsURI";
private static final String KEY_MODULES_URI= "moduleURI";
// Constructor
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Creating tables
*/
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_MODULE_TABLE = "CREATE TABLE "+ TABLE_MODULE + "("
+ KEY_MODULE_CODE +" TEXT PRIMARY KEY,"
+ KEY_MODULE_TITLE +" TEXT,"
+ KEY_MODULE_TIMETABLE +" TEXT,"
+ KEY_MODULE_SEMESTER +" TEXT);";
String CREATE_URIS_TABLE = "CREATE TABLE " + TABLE_URIS + "("
+ KEY_SERVER_URI + " TEXT PRIMARY KEY,"
+ KEY_NEWS_URI + " TEXT,"
+ KEY_MODULES_URI + " TEXT);";
db.execSQL(CREATE_MODULE_TABLE + CREATE_URIS_TABLE);
}
/**
* Upgrading database
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MODULE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_URIS);
//Create tables again
onCreate(db);
}
public void addModule(Module module) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_MODULE_TITLE, module.getTitle());
values.put(KEY_MODULE_CODE, module.getCode());
values.put(KEY_MODULE_TIMETABLE, module.getTimetable());
values.put(KEY_MODULE_SEMESTER, module.getSemester());
db.insert(TABLE_MODULE, null, values);
db.close(); // Closing database connection
}
/**
* Adding new server URIs
* @param uris
*/
public void addURIs(ServerURIs uris){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SERVER_URI, uris.getServerURI());
values.put(KEY_NEWS_URI, uris.getNewsURI());
values.put(KEY_MODULES_URI, uris.getModulesURI());
// Inserting Row
db.insert(TABLE_URIS, null, values);
db.close(); // Closing database connection
}
}
Uppon添加新的記錄到第二個表引發錯誤說,第二個表不存在。在的onCreate(活動代碼),將數據添加到數據庫中:
DatabaseHandler dbh = new DatabaseHandler(this);
dbh.addURIs(serverURLs);
不知道是什麼原因。先謝謝你。
清除您的數據或卸載您的應用程序並重新運行。 – 2013-04-09 18:09:54
聽起來像「你試圖把它打開和關閉?」))))謝謝你的男人,重新安裝幫助! :) – exomen 2013-04-09 18:14:12
修改數據庫時,不會調用onCreate,因爲數據庫已經存在。因此,您必須刪除數據庫才能再次調用onCreate。 – 2013-04-09 18:16:43