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

Python操作MySQL报Not all parameters were used in the SQL statement如何解决

问题产生原因
  • 占位符语法不匹配:mysql.connector 库的SQL参数占位符为 %s,你在查询员工ID是否存在的SELECT语句中使用了 ? 作为占位符,这是SQLite等其他数据库的语法,MySQL连接器无法识别,会把?当成普通字符处理,导致你传入的ID参数没有被用到,直接触发参数不匹配报错。
  • 插入逻辑未执行:你把插入员工的SQL语句和参数打包成了add_user元组后,没有调用cur.execute()执行该语句,参数没有被绑定到SQL中执行,就算解决了第一个问题也无法完成数据插入。
修复方法

修改两处核心问题即可,同时补充事务回滚和资源释放逻辑避免异常:

def add(self):
    myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "110277", database = "ims")
    cur=myconn.cursor()
    try:
        if self.var_emp_id.get()=='':
            messagebox.showerror('Error','Employee ID Must be required',parent=self.root)
        else:
            # 修复1:将查询语句的占位符?替换为%s
            cur.execute('SELECT * FROM employee WHERE eid=%s',(self.var_emp_id.get(),))
            row=cur.fetchone()
            if  row!=None:
                messagebox.showerror("Error","This Employee ID already assigned, try different",parent=self.root )
            else:
                add_user= ('INSERT INTO employee (eid,name,email,gender,contact,dob,doj,pass,utype,address,salary) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',(     
                            self.var_emp_id.get(),
                            self.var_name.get(),
                            self.var_email.get(),
                            self.var_gender.get(),
                            self.var_contact.get(),
                            self.var_dob.get(),
                            self.var_doj.get(),
                            self.var_pass.get(),
                            self.var_utype.get(),
                            self.txt_address.get('1.0',END),
                            self.var_salary.get(),
                ))
                # 修复2:执行插入语句,绑定参数
                cur.execute(*add_user)
                myconn.commit()
                messagebox.showinfo("Success","Employee Add Successfully",parent=self.root) 
    except Exception as ex:
        # 补充:出错时回滚事务,避免脏数据
        myconn.rollback()
        messagebox.showerror("Error",f"Error due  to: {str(ex)}",parent=self.root)
    finally:
        # 补充:关闭游标和连接,释放资源
        cur.close()
        myconn.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:36:02