为什么不是我的sqlite3外键工作? [英] Why aren't my sqlite3 foreign keys working?
问题描述
我从python解释器运行下面的代码,并期望insert语句失败并抛出某种异常。但是并没有发生:
$ py $ 2.6 $(r265:79096,Mar 19 2010,21:48:26)[MSC win32
上的v.1500 32位(Intel)]键入help,copyright,credits或license以获取更多信息。
>>> import sqlite3
>>> conn = sqlite3.connect(test.db)
>>> conn.executescript(
... pragma foreign_keys = on;
... begin transaction;
... create table t1(i integer key,a);
... create table t2(i,a,foreign key(i)references t1(i));
... commit;
...)
< ;在0x0229DAA0的sqlite3.Cursor对象>
>>> 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)]
>>> #但为什么!?
...
>>>
有谁知道为什么这不想工作?我的理解是插入应该失败,因为我为 t2(i)
赋予的值不是 t1 $ c $中的主键c>,但它很高兴地做到了这一点...?
在SQLite中使用外键支持是非常新的仅在10月14日的3.6.19发布。你确定你正在使用SQLite 3.6.19或更高版本吗?
检查sqlite3模块中的sqlite_version常量。例如。在Mac OS X 10.6系统上安装默认的python / sqlite:
>>> import sqlite3
>>> sqlite3.sqlite_version
'3.6.12'
>>>
I run the following code from a python interpreter, and expect the insert statement to fail and throw some kind of exception. But it's not happening:
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!?
...
>>>
Does anyone know why this doesn't want to work? My understanding is that the insert should fail since the value I gave for t2(i)
isn't a primary key in t1
, but it happily does it anyway...?
Working foreign key support in SQLite is very new -- it was only released in 3.6.19 on October 14th. Are you sure you're using SQLite 3.6.19 or later?
Check the sqlite_version constant in the sqlite3 module. E.g. on a Mac OS X 10.6 system with the default python/sqlite install:
>>> import sqlite3
>>> sqlite3.sqlite_version
'3.6.12'
>>>
这篇关于为什么不是我的sqlite3外键工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!