如何在非async函数中运行编辑aiosqlite数据库的while循环?
修复
await语法错误并实现定时数据库更新功能 问题场景
需要通过后台线程每秒对gwtimes.db中的time列所有值加50,并打印查询结果,但运行代码时出现语法错误。
原代码
if True: import shortcuts.startupload from shortcuts.startupload import * import threading import time def background(): while True: if 1 == 1: if 1 == 1: gwtimes = await aiosqlite.connect('gwtimes.db') async with gwtimes.cursor() as gwcursor: await gwcursor.execute("UPDATE gwtimes SET time=time+50") await gwtimes.commit() async with gwtimes.cursor() as gwcursor: await gwcursor.execute("SELECT time FROM gwtimes") number = await gwcursor.fetchone() print(number) def foreground(): # other code pass b = threading.Thread(name='background', target=background) f = threading.Thread(name='foreground', target=foreground) b.start() f.start() bot.run(hidden token)
报错信息
gwtimes = await aiosqlite.connect('gwtimes.db') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: 'await' outside async function
解决方法
错误核心是await关键字只能在**异步函数(用async修饰)**内使用,同时aiosqlite是异步数据库库,需要在事件循环中运行。具体修正步骤:
- 将
background函数改为异步函数,添加async关键字 - 在后台线程中启动异步事件循环,执行异步任务
- 添加
asyncio.sleep(1)实现每秒执行一次的逻辑 - 用
async with自动管理数据库连接和游标,避免资源泄漏
修正后的完整代码
if True: import shortcuts.startupload from shortcuts.startupload import * import threading import asyncio import aiosqlite # 确保显式导入aiosqlite async def background_task(): while True: # 异步连接数据库,自动管理连接生命周期 async with aiosqlite.connect('gwtimes.db') as gwtimes: # 执行更新操作 async with gwtimes.cursor() as gwcursor: await gwcursor.execute("UPDATE gwtimes SET time=time+50") await gwtimes.commit() # 查询所有time值并打印 async with gwtimes.cursor() as gwcursor: await gwcursor.execute("SELECT time FROM gwtimes") all_times = await gwcursor.fetchall() print(all_times) # 控制每秒执行一次 await asyncio.sleep(1) def background(): # 在后台线程中初始化并启动异步事件循环 loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(background_task()) def foreground(): # other code pass b = threading.Thread(name='background', target=background) f = threading.Thread(name='foreground', target=foreground) b.start() f.start() bot.run(hidden token)
关键说明
- 异步函数
background_task封装所有数据库操作,内部可正常使用await调用异步方法 - 普通函数
background作为线程入口,负责创建并运行异步事件循环 - 使用
fetchall()替代原代码的fetchone(),可获取所有行的time值,按需调整即可 async with语法自动处理连接和游标的关闭,避免资源泄漏
内容的提问来源于stack exchange,提问作者TheBlooner
相关产品推荐
相关产品推荐

