我正在使用一个库,该库通过调用 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/