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

Python程序执行数据库插入时报pymysql.err.ProgrammingError错误求助

解决pymysql.err.ProgrammingError: (1064) SQL语法错误

你的代码存在几个关键问题,直接导致了SQL语法错误和其他运行问题,以下是修正方案:

1. INSERT语句语法缺失

这是触发1064错误的核心原因。SQL的INSERT语句必须包含VALUES子句来指定要插入的具体数据,原代码只声明了列名,没有提供对应值。

2. 事务提交方式错误

不能通过cursor.execute("commit")提交事务,正确做法是调用数据库连接对象的commit()方法。

3. 大小写不一致问题

Python是大小写敏感语言,你前面用messagebox.showinfo,后面写成了MessageBox.showinfo,需要统一为小写的messagebox。

4. 提示文本拼写错误

"all field are requireds"存在拼写错误,修正为"all fields are required"。

修正后的完整代码

def insert():
    nomcomplet = entryName.get()
    adresse = entryadr.get()
    saison = entrySEM.get()
    nombre_de_chambre = entryCHEM.get()

    if nomcomplet == "" or adresse == "" or saison == "" or nombre_de_chambre == "" :
        messagebox.showinfo("insert status", "all fields are required")
    else :
        con = pymysql.connect(host='localhost', port=3307, user="root", password="", db="miniprojet", local_infile=True)
        cursor = con.cursor()
        # 用%s作为参数占位符,避免SQL注入同时修正语法
        sql = "INSERT INTO `moha` (nomcomplet, adresse, saison, nombre_de_chambre) VALUES (%s, %s, %s, %s)"
        cursor.execute(sql, (nomcomplet, adresse, saison, nombre_de_chambre))
        con.commit()  # 正确提交事务

        messagebox.showinfo("insert status", "inserted successfully")
        con.close()

补充说明:使用%s参数占位符不仅修正了语法,还能有效避免SQL注入风险,比直接拼接字符串更安全。

内容的提问来源于stack exchange,提问作者Mohamed Amine Laarif

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:25:14