我有一個表調用listTable和productTable。我在listTable中執行sqlite刪除功能,但在我的編碼中出現錯誤。 productTable內部具有對listTable中主鍵的外鍵引用。如果存在有產品列表內在sqlite表中執行刪除行
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String dbName = "shoppingDB1.db";
public static final int dbVersion = 1;
public static final String listTable = "ShoppingList";
public static final String listId = "ShopingList_Id";
public static final String listName = "ShopingList_Name";
public static final String productTable = "Product";
public static final String product_id = "Product_Id";
public static final String productName = "Product_Name";
public static final String product_FId = "Product_FId";
private static final String CREATE_SHOPPLINGLIST_TABLE = "CREATE TABLE IF NOT EXISTS "
+ listTable
+ " ("
+ listId
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ listName
+ " TEXT ")";
private static final String CREATE_PRODUCT_TABLE = "CREATE TABLE IF NOT EXISTS "
+ productTable
+ " ("
+ product_id
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ productName
+ " TEXT, "+ product_FId
+ " INTEGER NOT NULL, "
FOREIGN KEY ("
+ product_FId
+ ") REFERENCES "
+ listTable
+ " ("
+ listId
+ ")
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SHOPPLINGLIST_TABLE);
db.execSQL(CREATE_PRODUCT_TABLE);
}
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
ComicsData.java
public class ComicsData {
public ComicsData(Context context) {
dbHelper = new SQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void deleteList(String myid) {
// TODO Auto-generated method stub
String[] arg={myid};
try{
database.delete(SQLiteHelper.listTable, SQLiteHelper.listId+ " = ?",arg);
}catch(Exception e){
Log.e("cannot", e.toString());
}
}
錯誤消息
12-02 17:27:46.232: E/error(21668): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
deleteList(字符串本身份識別碼)將會顯示錯誤。 有人知道我的問題是什麼?應該是外鍵問題。我將listId傳遞給deleteList(String myid)
你什麼錯誤,到底是什麼? – Simon
我不能刪除列表,如果我添加產品裏面列表 12-02 17:24:04.936:E /不能(21033):android.database.sqlite.SQLiteConstraintException:錯誤代碼19:約束失敗 – johnk
我覺得它的外鍵約束錯誤。編寫一個查詢以從表中刪除Product_FId和ListID。試試吧,它應該可以工作 – Priety