我正在使用一个通过调用sqlite3.connect(':memory:')
在内存中创建SQLite库的库。我想连接到这个数据库使用sqlalchemy
使用一些对象关系管理和其他漂亮的铃声和口哨。在SQLAlchemy的深层,有没有一种方法可以传递产生的sqlite3.Connection
对象,以便我可以重用它?
我不能仅仅用connection = sqlalchemy.create_engine('sqlite:///:memory:').connect()
重新连接--正如SQLite documentation所说的:“一旦数据库连接关闭,数据库就不复存在了。Every :memory: database与其他数据库不同。因此,打开两个文件名为":memory:“的数据库连接将创建两个独立的内存中数据库。(这是有道理的。我也试过了,行为和预期的一样。)
我尝试按照SQLAlchemy的源代码查找建立数据库连接和实际调用SQLite的低级位置,但到目前为止我什么也没找到。看起来SQLAlchemy使用了太多晦涩难懂的炼金术来做到这一点,我无法理解它发生的时间和地点。
发布于 2020-05-25 05:25:24
这里有一种方法可以做到:
# 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。
https://stackoverflow.com/questions/61991050
复制相似问题