我有一个表调用listTable和productTable。我在listTable中执行sqlite删除功能,但我的编码有问题。 inside productTable在listTable中有对主键的外键引用。
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(String myid)将显示错误。 有谁知道我的问题是什么?应该是外键问题。我将listId传递给deleteList(String myid)
答案 0 :(得分:0)
您的产品将列表ID作为外键。您无法删除包含产品的列表,因为具有该列表ID作为外键的所有产品将属于不存在的列表。
您已在(db.execSQL("PRAGMA foreign_keys=ON;");
)上设置了约束,因此SQLite不允许您执行此操作并抛出您看到的异常。
换句话说,约束表明所有具有列表ID的产品必须引用现有列表。
要解决此问题,您可以取消引用要删除的列表的所有productTable.listID。要自动执行此操作,请将ON DELETE SET NULL
添加到约束中。
你应该读到这个: