为什么我的sqlite3外键不起作用?


问题内容

我从python解释器运行以下代码,并期望insert语句失败并引发某种异常。但这没有发生:

Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> conn = sqlite3.connect("test.db")
>>> conn.executescript("""
... pragma foreign_keys=on;
... begin transaction;
... create table t1 (i integer primary key, a);
... create table t2 (i, a, foreign key (i) references t1(i));
... commit;
... """)
<sqlite3.Cursor object at 0x0229DAA0>
>>> c = conn.cursor()
>>> c.execute("insert into t2 values (6, 8)")
<sqlite3.Cursor object at 0x0229DAD0>
>>> #???
...
>>> conn.commit()
>>> #???????????
...
>>> c.execute("select * from t2")
<sqlite3.Cursor object at 0x0229DAD0>
>>> c.fetchall()
[(6, 8)]
>>> #but why!?
...
>>>

有谁知道为什么这不起作用?我的理解是,插入操作应该失败,因为我提供的值t2(i)不是in中的主键t1,但是无论如何它还是很高兴…?


问题答案:

在SQLite中工作外键支持是非常新的-它仅在10月14日于3.6.19中发布。您确定使用的是SQLite 3.6.19或更高版本吗?

检查sqlite3模块中的sqlite_version常量。例如,在具有默认python / sqlite安装的Mac OS X 10.6系统上:

>>> import sqlite3
>>> sqlite3.sqlite_version
'3.6.12'
>>>