gpt4 book ai didi

python - 重用 aiosqlite 连接

转载 作者:行者123 更新时间:2023-12-01 18:41:56 25 4
gpt4 key购买 nike

我只是不知道如何使用 aiosqlite 模块,以便我可以保持连接以供以后使用。

基于 aiosqlite project page 的示例

async with aiosqlite.connect('file.db') as conn:
cursor = await conn.execute("SELECT 42;")
rows = await cursor.fetchall()
print('rows %s' % rows)

工作正常,但我想保持连接,以便我可以在整个程序中使用它。

通常,使用 sqlite,我会打开一个连接,将其存储起来,然后在程序的整个生命周期中使用它。

我还尝试过以下方法:

conn = aiosqlite.connect('file.db')
c = await conn.__enter__()
AttributeError: 'Connection' object has no attribute '__enter__'

有没有办法在没有上下文管理器的情况下使用这个模块?

最佳答案

“最佳”方法是应用程序的入口点使用上下文管理器方法创建 aiosqlite 连接,在某处存储对连接对象的引用,然后从内部运行应用程序的“runloop”方法那个背景。这将确保当您的应用程序退出时,sqlite 连接被适本地清理。这可能看起来像这样:

async def main():
async with aiosqlite.connect(...) as conn:
# save conn somewhere
await run_loop()

或者,您可以等待适当的进入/退出方法:

try:
conn = aiosqlite.connect(...)
await conn.__aenter__()
# do stuff
finally:
await conn.__aexit__()

无论如何,请注意 aiosqlite 的异步特性确实意味着共享连接可能会导致事务重叠。如果您需要确保并发查询通过单独的事务进行,那么您将需要每个事务有一个单独的连接。

根据Python sqlite docs关于共享连接:

When using multiple threads with the same connection writing operations should be serialized by the user to avoid data corruption.

这同样适用于 aiosqlite 和 asyncio。例如,以下代码可能会将两个插入重叠到单个事务中:

async def one(db):
await db.execute("insert ...")
await db.commit()

async def two(db):
await db.execute("insert ...")
await db.commit()

async def main():
async with aiosqlite.connect(...) as db:
await asyncio.gather(one(db), two(db))

这里正确的解决方案是为每个事务创建一个连接,或者使用诸如 executescript 之类的东西立即执行整个事务。

关于python - 重用 aiosqlite 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53908615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com