代码之家  ›  专栏  ›  技术社区  ›  Carson Myers

为什么sqlite3外键不起作用?

  •  6
  • Carson Myers  · 技术社区  · 15 年前

    我从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) t1 ,但不管怎样,它还是很高兴的。。。?

    2 回复  |  直到 15 年前
        1
  •  9
  •   Nicholas Knight    15 年前

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

    >>> import sqlite3
    >>> sqlite3.sqlite_version
    '3.6.12'
    >>> 
    
        2
  •  4
  •   Charitoo    9 年前

    正如Nicholas所说,检查您的sqlite版本是否支持外键。如果sqlite的版本大于或等于3.6.19,这并不重要。可以在关闭外键支持的情况下编译源代码。要检查并执行以下命令。

    cursor.execute(“PRAGMA外键”)

    如果它不返回任何数据,那么您的版本就没有外键支持。

    到目前为止,sqlite3中还没有强制执行外键支持。退房 here .