外键约束在sqlite3中不起作用[重复]

gkl3eglg  于 2022-12-23  发布在  SQLite
关注(0)|答案(1)|浏览(168)
    • 此问题在此处已有答案**:

Foreign Key constraint doesn't work(1个答案)
昨天关门了。

  • python版本:3.8.10
  • sqlite3.version:2.6.0
  • sqlite3.sqlite_version:3.31.1

我有两张table:blocklistblocklist_reasons。请参见以下内容:

blocklist_reasons
id | reason
--------------------------
1  | Source not supported

blocklist
id | link            | reason
-----------------------------
1  | https://mega.nz | 1

blocklist.reason引用blocklist_reasons.id,因此设置了外键约束。
但是,我可以插入任何我想要的数字,它仍然会接受,这很奇怪:

sqlite> INSERT INTO blocklist(link, reason) VALUES ('https://example.com', 2);
sqlite> -- No problems eventhough there is no row in blocklist_reasons with ID 2???
sqlite> SELECT * FROM blocklist;
1|https://mega.nz|1
2|https://example.com|2

我可以用下面的代码重现这个问题:

-- Create reasons table and add one reason with ID 1
CREATE TABLE blocklist_reasons(
    id INTEGER PRIMARY KEY,
    reason TEXT NOT NULL UNIQUE
);
INSERT INTO blocklist_reasons(reason) VALUES ('Source not supported');
SELECT * FROM blocklist_reasons;
1|Source not supported

-- Create blocklist table and insert row with reason ID set as ID 2 without errors
CREATE TABLE blocklist(
    id INTEGER PRIMARY KEY,
    link TEXT NOT NULL,
    reason INTEGER NOT NULL,
    FOREIGN KEY (reason) REFERENCES blocklist_reasons(id)
);
INSERT INTO blocklist(link, reason) VALUES ('https://mega.nz', 2);
SELECT * FROM blocklist;
1|https://mega.nz|2

您可以看到,我插入了reason列设置为2的行,即使blocklist_reasons表中没有ID为2的行,也能正常工作。为什么外键约束没有引发错误?

muk1a3rh

muk1a3rh1#

原来我必须 ENABLE 外键检查。在我看来很愚蠢,但还不错。每次启动数据库连接(不是游标连接,而是数据库连接)时,运行以下命令:

PRAGMA foreign_keys = ON;

这将启用约束。

相关问题