2012-10-24 30 views
2

我有一個SqliteConstraintException異常。 我的數據庫就是這樣SqliteConstraintException Android

private static final String CREATE_TABLE_1 = 
    "create table table_1 (uid integer primary key autoincrement, " 
+ table_1.c1 + " TEXT," 
+ table_1.c2 + " integer," 
+ table_1.c3 + " TEXT," 
+ table_1.c4 + " TEXT," 
+ table_1.c5 + " integer);"; 

private static final String CREATE_TABLE_2 = 
     "create table table_2 (uid integer primary key autoincrement, " 
+ table_2.c1 + " TEXT," 
+ table_2.c2 + " integer," 
+ table_2.c3 + " TEXT);"; 

private static final String CREATE_TABLE_3 = 
     "create table table_3 (uid integer primary key autoincrement, " 
     + "uid_table_1 integer, " 
     + "uid_table_2 integer, " 

+ "FOREIGN KEY(uid_table_1) REFERENCES table_1(uid) ON DELETE CASCADE, " 
+ "FOREIGN KEY(uid_table_2) REFERENCES table_2(uid) ON DELETE CASCADE);"; 

private static final String CREATE_TABLE_4 = 
     "create table table_4 (uid integer primary key autoincrement, " 
+ "uid_table_2 integer," 
+ "FOREIGN KEY(uid_table_2) REFERENCES table_2(uid) ON DELETE CASCADE);"; 

而且我在SQLiteOpenHelper用於啓用外鍵約束

@Override 
public void onOpen(SQLiteDatabase db) { 
super.onOpen(db); 
if (!db.isReadOnly()) { 
// Enable foreign key constraints 
db.execSQL("PRAGMA foreign_keys=ON;"); 
} 

但是,當我要刪除的TABLE_2的行,我得到SqliteConstraintException。 你能幫我嗎?

謝謝

回答

0

我看起來像極了你的表的相互引用。如果要刪除表2中用作其他表中的外鍵的行,則需要刪除引用它的記錄。因此刪除表3和4中的記錄,該記錄對外部關鍵字引用了您要在2中刪除的行,然後對該行調用delete。

+0

謝謝你的回答。 – Hasina

+0

不要忘記接受,如果它適合你 – toadzky

+0

所以這是正確的,如果我這樣做'mDb.beginTransaction(); \t \t嘗試{ \t \t \t mDb.delete(「table_3」,「uid_table_2 =」+ uid,null); \t \t \t mDb.delete(「table_4」,「uid_table_2 =」+ uid,null); \t \t \t this.mDb.delete(「table_2」,「uid =」+ uid,null); \t \t}趕上(例外五){ \t \t \t \t } \t最後{ \t \t \t mDb.endTransaction(); \t \t}' – Hasina

相關問題