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

Why aren#39;t my sqlite3 foreign keys working?(为什么我的 sqlite3 外键不起作用?)
本文介绍了为什么我的 sqlite3 外键不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!?
...
>>>

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

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...?

推荐答案

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

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?

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

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 外键不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
FastAPI + Tortoise ORM + FastAPI Users (Python) - Relationship - Many To Many(FastAPI+Tortoise ORM+FastAPI用户(Python)-关系-多对多)
Inserting NaN value into MySQL Database(将NaN值插入MySQL数据库)
How to define composite foreign key mapping in hibernate?(如何在Hibernate中定义复合外键映射?)
Window functions not working in pd.read_sql; Its shows error(窗口函数在pd.read_sql中不起作用;它显示错误)
(Closed) Leaflet.js: How I can Do Editing Geometry On Specific Object I Select Only?((已关闭)Leaflet.js:如何仅在我选择的特定对象上编辑几何图形?)