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

使用UPDATE语句时出现MySQL编程错误:WHERE子句列名识别异常

解决MySQL更新语句参数顺序错误导致的1054错误

问题重现

调用Guardar_Modificaciones执行用户数据更新时,触发以下错误:

mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'CARRERA' in 'where clause'

其中CARRERA是Direccion字段的实际值,并非ID字段内容。

错误原因

modificar_usuario函数中的SQL语句使用format拼接时,参数顺序完全错误:

  • SQL的SET部分需要10个字段值(Nombre到Direccion),WHERE部分需要1个ID值
  • 但format的参数顺序是ID在前,随后是10个字段值,导致WHERE ID = {}最终被替换成Direccion的值(即CARRERA)
  • 由于字符串未加引号,MySQL将CARRERA识别为列名,因此抛出"未知列"错误

解决方案

方案1:修正参数拼接顺序

调整format的参数顺序,将ID放在最后,对应WHERE子句的占位符:

def modificar_usuario(self, ID, Nombre, HA, Identificacion, Edad, FNacimiento, Escolaridad, SS, Etnia, Contacto, Direccion):
    cur = self.cnn.cursor()
    # 调整format参数顺序,将ID放在最后匹配WHERE的占位符
    sql='''UPDATE usuarios SET Nombre='{}', HA='{}', Identificacion='{}', Edad='{}', FNacimiento='{}', Escolaridad='{}', SS='{}', Etnia='{}', Contacto='{}',
    Direccion='{}' WHERE ID = {} '''.format(Nombre, HA, Identificacion, Edad, FNacimiento, Escolaridad, SS, Etnia, Contacto, Direccion, ID)
    cur.execute(sql)
    n=cur.rowcount
    self.cnn.commit()
    cur.close()
    return n

方案2:使用参数化查询(推荐)

直接使用MySQL连接器的参数化查询功能,避免手动拼接字符串的顺序错误,同时防止SQL注入:

def modificar_usuario(self, ID, Nombre, HA, Identificacion, Edad, FNacimiento, Escolaridad, SS, Etnia, Contacto, Direccion):
    cur = self.cnn.cursor()
    # 使用%s作为参数占位符,参数通过元组传入execute
    sql='''UPDATE usuarios SET Nombre=%s, HA=%s, Identificacion=%s, Edad=%s, FNacimiento=%s, Escolaridad=%s, SS=%s, Etnia=%s, Contacto=%s,
    Direccion=%s WHERE ID = %s '''
    cur.execute(sql, (Nombre, HA, Identificacion, Edad, FNacimiento, Escolaridad, SS, Etnia, Contacto, Direccion, ID))
    n=cur.rowcount
    self.cnn.commit()
    cur.close()
    return n

另外,Guardar_Modificaciones中的提示信息有误,建议修正为对应操作的提示:

def Guardar_Modificaciones(self):
    self.usuario.modificar_usuario(self.ID, self.txtNombre.get(), self.txtHA.get(),self.txtIdentificacion.get(),self.txtEdad.get(),self.txtFNacimiento.get(),self.txtEscolaridad.get(),self.txtSS.get(),self.txtEtnia.get(),self.txtContacto.get(),self.txtDireccion.get())
    messagebox.showinfo("Modificar", 'Elemento modificado correctamente')

内容的提问来源于stack exchange,提问作者Adrián Guerao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:45:32