python - SQLite/SQLAlchemy : how to enforce Foreign Keys?

标签 python sqlite foreign-keys sqlalchemy

新版本的 SQLite 能够强制执行外键约束,但为了向后兼容,您必须为每个数据库连接单独启用它!

sqlite> PRAGMA foreign_keys = ON;

我正在使用 SQLAlchemy ——我如何确保它始终打开? 我尝试过的是这样的:

engine = sqlalchemy.create_engine('sqlite:///:memory:', echo=True)
engine.execute('pragma foreign_keys=on')

...但它不起作用!...我错过了什么?

编辑: 我认为我真正的问题是我安装了多个版本的 SQLite,而 Python 没有使用最新的版本!

>>> import sqlite3
>>> print sqlite3.sqlite_version
3.3.4

但是我刚刚下载了3.6.23并将exe放在我的项目目录中! 我怎样才能找出它正在使用哪个.exe,并更改它?

最佳答案

对于最新版本 (SQLAlchemy ~0.7) SQLAlchemy homepage说:

PoolListener is deprecated. Please refer to PoolEvents.

那么 CarlS 的例子就变成了:

engine = create_engine(database_url)

def _fk_pragma_on_connect(dbapi_con, con_record):
    dbapi_con.execute('pragma foreign_keys=ON')

from sqlalchemy import event
event.listen(engine, 'connect', _fk_pragma_on_connect)

关于python - SQLite/SQLAlchemy : how to enforce Foreign Keys?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54292038/

相关文章:

python pyplot注释

ios - 如何使用 FMDB 正确获取 lastRowId?

python - MySQL - 无法定义外键

postgresql - 涉及多个表的外键约束

java - Hibernate:没有实体类的外键,只能通过id

Python:我试图找到列表中两个元素之间的最大差异

python - 如何计算Python中的单词数达到限制?

python - 无法从 keras.utils 导入 plot_model?

Android sqlite getdatabase 递归调用

python - 如何修复 python sqlite 中的 'sqlite3.OperationalError: near "?": ' 错误?