You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python SQL循环首次执行时反复出现Unread result found错误

解决mysql-connector-python "Unread result found" 错误

错误原因

Unread result found 异常是因为当前数据库连接上存在未完全读取的结果集。当尝试创建新游标时,连接器会检测到连接状态未清理,从而抛出该异常。问题并非出在retrieve_records函数本身,而是其他数据库操作(比如扫码存数据的逻辑)未正确处理结果集,导致连接被未读结果占用,首次调用retrieve_records时触发错误。

解决方案

1. 全局清理未读结果

如果必须复用全局数据库连接,在创建游标前强制清理连接中残留的未读结果:

def retrieve_records():
    try:
        # 清理连接中未读的结果集
        if conn.unread_result:
            conn.consume_results()
        
        cursor = conn.cursor(buffered=True)
        cursor.execute(f"SELECT * FROM {scanner.table_name}")
        records = cursor.fetchall()
        tree.delete(*tree.get_children())

        for record in records:
            tree.insert("", "end", values=record)
        
        cursor.close()
    except mysql.connector.Error as err:
        messagebox.showerror("Error", f"获取记录时出错: {err}")

2. 使用上下文管理器自动管理游标

用with语句创建游标,确保游标自动关闭,避免资源残留:

def retrieve_records():
    try:
        with conn.cursor(buffered=True) as cursor:
            cursor.execute(f"SELECT * FROM {scanner.table_name}")
            records = cursor.fetchall()
            tree.delete(*tree.get_children())
            for record in records:
                tree.insert("", "end", values=record)
        # with块结束后游标自动关闭,无需手动调用close()
    except mysql.connector.Error as err:
        messagebox.showerror("Error", f"获取记录时出错: {err}")

3. 检查所有数据库操作代码

排查扫码存数据等其他数据库操作逻辑,确保:

  • 所有查询操作的结果集都通过fetchall()/fetchone()/fetchmany()读取完毕
  • 执行存储过程或多结果集SQL时,用while cursor.nextset(): pass消费所有结果
  • 每次操作后及时关闭游标,或用上下文管理器管理资源

内容的提问来源于stack exchange,提问作者Chauhan Mukesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:42:57