异步 SQLite python

问题描述 投票:0回答:1

我使用 aiogram 库编写异步电报机器人。我决定使用 SQLite 作为存储不可变值的数据库。如何从我的数据库中实现异步读取?

python python-3.x sqlite python-asyncio telegram-bot
1个回答
25
投票

sqlite3
模块的包装已经存在,你应该在你的异步代码中使用它。

或者,您可以通过将同步调用包装在

run_in_executor
中将它们转换为异步调用。例如:

async def fetchall_async(conn, query):
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(
        None, lambda: conn.cursor().execute(query).fetchall())

这为您提供了一个可以从异步代码中调用的协程,而不必担心长时间运行的执行会阻塞整个事件循环:

async def some_task():
    ...
    students = await fetchall_async(conn, "select * from students")

但是把它留给一个经过良好测试的包是一个更好的主意。

© www.soinside.com 2019 - 2024. All rights reserved.