【问题标题】:SqliteConstraintException AndroidSqliteConstraintException Android
【发布时间】:2012-10-24 16:45:22
【问题描述】:

我遇到了 SqliteConstraintException 的问题。 我的数据库是这样的

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。 你能帮帮我吗?

谢谢

【问题讨论】:

    标签: android sqlite exception


    【解决方案1】:

    我看起来您的大多数表格都相互引用。如果要删除表 2 中用作不同表中的外键的行,则需要删除引用它的记录。所以从表 3 和 4 中删除记录,这些记录具有指向您尝试在 2 中删除的行的外键引用,然后为该行调用 delete。

    【讨论】:

    • 所以如果我这样做是正确的mDb.beginTransaction(); try{ mDb.delete("table_3", "uid_table_2=" + uid, null); mDb.delete("table_4", "uid_table_2=" + uid, null); this.mDb.delete("table_2", "uid = " + uid, null); }catch(Exception e){ }finally{ mDb.endTransaction(); }
    • 我忘记添加mDb.setTransactionSuccessful();
    • 如果我理解正确,您不需要开始或结束交易。每个调用都会自动包装在事务中。我唯一一次手动操作是如果我在循环中修改数据库。开始一个事务,执行几百个插入或删除,然后结束它可以明显更快 - 但只有几个,它不会让你得到太多,但会让你的代码更加混乱
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 2011-03-26
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多