python - 使用 sqlalchemy 连接到 sqlite3.Connection

标签 python sqlite sqlalchemy

我正在使用一个库,该库通过调用 sqlite3.connect(':memory:') 在内存中创建 SQLite 库。我想使用 sqlalchemy 连接到这个数据库,以使用一些 ORM 和其他漂亮的功能。在 SQLAlchemy 的 API 深处,是否有一种方法可以传递生成的 sqlite3.Connection 对象,以便我可以重新使用它?

我不能仅使用 connection = sqlalchemy.create_engine('sqlite:///:memory:').connect() 重新连接 – 作为 SQLite documentation状态:“一旦数据库连接关闭,数据库就不再存在。每个 :memory: 数据库都彼此不同。因此,打开两个文件名分别为“:memory:”的数据库连接将创建两个独立的内存数据库。” (这是有道理的。我也尝试过,并且行为符合预期。)

我试图按照 SQLAlchemy 的源代码来找到建立数据库连接和实际调用 SQLite 的低级位置,但到目前为止我什么也没找到。看起来 SQLAlchemy 使用了太多晦涩难懂的炼金术来做到这一点,让我无法理解它发生的时间和地点。

最佳答案

这是一种方法:

# some connection is created - by you or someone else 
conn = sqlite3.connect(':memory:')

... 

def get_connection():
    # just a debug print to verify that it's indeed getting called:
    print("returning the connection") 
    return conn

# create a SQL Alchamy engine that uses the same in-memory sqlite connection
engine = create_engine('sqlite://', creator = get_connection)

从现在开始,你就可以随心所欲地使用引擎了。

这是a link to the documentation的这个功能。

关于python - 使用 sqlalchemy 连接到 sqlite3.Connection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61991050/

相关文章:

python - 匹配由字符串的开头和结尾或非单词字符绑定(bind)的单词的正则表达式

python - 在 MySQL 中创建名为 0e7cc62d5339491aa701b67453405ccb 的表时出错

javascript - sqlite3 - 插入 - javascript 对象作为值

sql - 比较SQLite中的两个表

SQLAlchemy - 带索引的建表语句

python - PyTorch LSTM : RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. 在维度 1 中得到 1219 和 440

python - 无法 reshape 包含 PNG 图像的 numpy 数组

c++ - 使用 C++ 可以从方法返回 sqlite3_stmt 吗?

python - 没有 session 、事务的sqlalchemy orm

python - SqlAlchemy/Sqlite距离计算