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

如何为Python MySQL代码添加缓冲解决Unread result found错误?

解决mysql.connector.errors.InternalError: Unread result found错误及配置缓冲方法

错误原因

你遇到的Unread result found错误,是因为使用非缓冲游标执行查询后,只读取了部分结果(比如fetchone()只取了第一条),剩余结果未读取就执行下一个数据库操作,导致连接器报错。

配置缓冲的两种方法

方法1:创建游标时启用缓冲(推荐)

在初始化游标时,添加buffered=True参数,游标会先把所有查询结果缓存到本地,后续操作不会受未读结果影响。

修改你的DataBase类的__init__方法:

def __init__(self):
    self.connection = mysql.connector.connect(
        host='',
        user='',
        password='',
        db=''
    )
    # 添加buffered=True启用缓冲游标
    self.cursor = self.connection.cursor(buffered=True)
    print("Ha funcionat")

方法2:全局启用缓冲(连接时配置)

如果想让所有游标默认启用缓冲,可以在连接数据库时设置buffered=True:

self.connection = mysql.connector.connect(
    host='',
    user='',
    password='',
    db='',
    buffered=True
)
self.cursor = self.connection.cursor()

代码其他问题修复

除了缓冲问题,你的代码还有几个关键问题需要修正:

  1. SQL注入风险:直接拼接用户输入到SQL语句中存在安全隐患,必须用参数化查询。
  2. INSERT操作未提交事务:执行插入后需要调用self.connection.commit(),否则数据不会真正写入数据库。
  3. update_user方法中的错误代码:users = self.cursor(buffered=True)是错误用法,INSERT操作不需要读取结果。

完整修复后的代码

import mysql.connector
from mysql.connector import Error

class DataBase:
    def __init__(self):
        self.connection = mysql.connector.connect(
            host='',
            user='',
            password='',
            db=''
        )
        # 启用缓冲游标
        self.cursor = self.connection.cursor(buffered=True)
        print("Ha funcionat")

    def select_user(self):
        sql = "SELECT * FROM Diccionari"
        try:
            self.cursor.execute(sql)
            user = self.cursor.fetchone()
            print(user)
        except Exception as e:
            raise

    def select_llenguatje(self):
        lenguaje = input("Seleccione el lenguaje : ")
        # 参数化查询避免SQL注入
        sql = "SELECT * FROM Diccionari WHERE Lenguaje = %s"
        try:
            self.cursor.execute(sql, (lenguaje,))
            user = self.cursor.fetchone()
            print(user)
        except Exception as a:
            raise

    def update_user(self):
        lenguaje1 = input("Posa el llenguatje: ")
        comandos = input("Posa el Comandos: ")
        descripcion = input("Posa el Descripcion: ")
        notas = input("Posa el Notas: ")
        # 参数化INSERT语句
        sql = """INSERT INTO Diccionari (Lenguaje, Comandos, Descripcion, Notas) 
                 VALUES (%s, %s, %s, %s)"""
        try:
            self.cursor.execute(sql, (lenguaje1, comandos, descripcion, notas))
            # 提交事务确保数据写入
            self.connection.commit()
            print("数据插入成功")
        except Exception as u:
            # 出错时回滚事务
            self.connection.rollback()
            raise

    def close(self):
        self.connection.close()
        print("Se ha cerrado la conexion")

database = DataBase()
database.select_user()
# 移除重复输入,方法内部已包含交互
database.select_llenguatje()
database.update_user()
database.close()

关键修改说明

  • 游标初始化添加buffered=True,解决未读结果错误。
  • 所有涉及用户输入的SQL语句改用参数化查询(%s作为占位符),避免SQL注入。
  • update_user方法添加commit()提交事务,出错时rollback()回滚。
  • 删除了select_llenguatje方法外的重复输入语句,避免冗余交互。

内容的提问来源于stack exchange,提问作者Martí RIbalta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:45:31