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

Python操作MySQL执行UPDATE语句报1064 SQL语法错误问题咨询

问题原因
  • 核心错误是你混用了Python字符串格式化和MySQL官方驱动的参数化查询占位符规则,同时存在3处具体问题:
  1. UPDATE语句中你手动给字符串占位符%s加了双引号"%s",参数化查询会自动处理字符串类型参数的引号包裹、特殊字符转义,你手动加引号会导致最终生成的SQL语法异常。
  2. 所有cursor.execute()调用都使用Python的%操作符拼接SQL字符串,这是不符合mysql.connector使用规范的用法,且极易引发SQL注入风险。正确用法是将参数作为execute的第二个参数(元组类型)传入,驱动会自动完成参数的安全替换。
  3. 最后执行查询语句cursor.execute(sql_select_query)时未传入id参数,也会触发语法错误。

至于报错信息里提到MariaDB,属于MySQL生态通用报错提示内容,和你实际使用的数据库类型无关,无需在意。

修正后代码
import mysql.connector

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='mydb',
                                         user='root',
                                         password='')
    cursor = connection.cursor()

    username = 1111111 #示例

    isian = "tryfile.pkl" #示例,需传入字符串类型数据

    print("Before updating a record ")
    sql_select_query = """select * from signature where id = %s"""
    # 参数作为execute第二个参数传入,注意单元素元组末尾要加逗号
    cursor.execute(sql_select_query, (username,))
    record = cursor.fetchone()
    print(record)

    # 更新单条记录 占位符不需要手动加引号
    sql_update_query = """Update signature set signature = %s where id = %s"""
    # 同样传入参数元组
    cursor.execute(sql_update_query, (isian, username))
    connection.commit()
    print("Record Updated successfully ")

    print("After updating record ")
    # 传入查询参数
    cursor.execute(sql_select_query, (username,))
    record = cursor.fetchone()
    print(record)
    
except mysql.connector.Error as error:
    print("Failed to update table record: {}".format(error))
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:54:03