使用aiosqlite遇ValueError: no active connection错误求助
问题原因
你代码里的db()函数用了async with上下文管理器,这个管理器会在代码块执行完后自动关闭数据库连接,所以当inventory()拿到返回的con时,连接已经断开了,调用con.cursor()自然会报ValueError: no active connection。
修正方案
有两种简单的修正方式,选一种就行:
方案一:直接在业务函数里用async with管理连接
把数据库操作直接放在async with块里,让上下文管理器自动处理连接的创建和关闭,最省心:
import aiosqlite async def inventory(): # async with会自动创建连接,执行完代码块后自动关闭 async with aiosqlite.connect('inventory.db') as con: cursor = await con.cursor() # 建议加IF NOT EXISTS,避免重复创建表时报错 await cursor.execute("CREATE TABLE IF NOT EXISTS inventory (user, dupes, name, char, rarity, image1, thumbnail1, image2, thumbnail2, UNIQUE (user, name, char))") await con.commit()
方案二:调整db函数的写法
如果想保留db()函数,不要在里面用async with,直接返回活跃的连接,然后在业务函数里手动管理关闭:
import aiosqlite async def db(): # 直接创建连接并返回,不使用async with return await aiosqlite.connect('inventory.db') async def inventory(): con = await db() try: cursor = await con.cursor() await cursor.execute("CREATE TABLE IF NOT EXISTS inventory (user, dupes, name, char, rarity, image1, thumbnail1, image2, thumbnail2, UNIQUE (user, name, char))") await con.commit() finally: # 用try-finally确保无论是否报错,连接都会被关闭 await con.close()
额外提示
- 加
IF NOT EXISTS是因为如果表已经存在,再次执行CREATE TABLE会报错,这是SQL的常用写法。 - 不需要手动关闭cursor,关闭连接时cursor会自动被清理。
内容的提问来源于stack exchange,提问作者joe bergeron
相关产品推荐
相关产品推荐

