JDBC忽略SQLite外键约束ON DELETE操作

时间:2014-11-26 16:38:09

标签: sqlite jdbc

我有一个包含以下结构的Rate表:

CREATE TABLE Rate (
id INTEGER PRIMARY KEY AUTOINCREMENT,
book_id INTEGER, 
value INTEGER,
user_id INTEGER,
FOREIGN KEY(user_id) REFERENCES  User(ID),
FOREIGN KEY(book_id) REFERENCES  book(ID) ON DELETE RESTRICT

具有以下结构的书桌:

DROP TABLE IF EXISTS Book;
CREATE TABLE Book (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT UNIQUE NOT NULL,
    ISBN VARCHAR,
    author_id INTEGER,
    editor_id INTEGER,
    translator_id INTEGER,
    publisher_id INTEGER,
    "type" VARCHAR,
    language VARCHAR,
    "date" VARCHAR, 
    format VARCHAR, 
    summary TEXT,


    FOREIGN KEY(author_id) REFERENCES Author(ID)    ON DELETE SET NULL ON UPDATE CASCADE, 
    FOREIGN KEY(editor_id) REFERENCES Editor(ID)    ON DELETE SET NULL ON UPDATE CASCADE, 
    FOREIGN KEY(translator_id) REFERENCES Translator(ID)    ON DELETE SET NULL ON UPDATE CASCADE,
    FOREIGN KEY(publisher_id) REFERENCES Publisher(ID)  ON DELETE SET NULL ON UPDATE CASCADE


);

所以,如果我有这样的Rate条目:

1 1 4 3(ID, BOOK_ID, VALUE, USER_ID)

我不应该删除ID为1的图书,对吧? 这正是当我尝试在SQLITE Manager上删除ID为1的Book时发生的情况。它给了我 FOREIGN KEY约束失败

然而,当我从代码中调用我的删除时,它完全忽略了限制并删除了该书,并且它仍然没有变化的条目:

  

1 1 4 3

我的删除方法如下:

public void delete() {
        try {
            String query = "DELETE FROM book WHERE id = ? ";
            PreparedStatement statement = db.prepareStatement(query);
            statement.setInt(1, (Integer) this.id);
            statement.executeUpdate();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

当我在SQLITE Manager上运行PRAGMA foreign_keys时,它返回1.因此,我认为数据库是正确创建的。

1 个答案:

答案 0 :(得分:2)

documentation说:

  

...外键约束...必须仍然由应用程序在运行时使用PRAGMA foreign_keys命令启用。例如:

PRAGMA foreign_keys = ON;
     

默认情况下禁用外键约束(为了向后兼容),因此必须为每个数据库连接单独启用。