- 此问题在此处已有答案**:
Foreign Key constraint doesn't work(1个答案)
昨天关门了。
- python版本:3.8.10
sqlite3.version
:2.6.0sqlite3.sqlite_version
:3.31.1
我有两张table:blocklist
和blocklist_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的行,也能正常工作。为什么外键约束没有引发错误?
1条答案
按热度按时间muk1a3rh1#
原来我必须 ENABLE 外键检查。在我看来很愚蠢,但还不错。每次启动数据库连接(不是游标连接,而是数据库连接)时,运行以下命令:
这将启用约束。