使用Tkinter向数据库录入数据失败:无报错但数据未保存
问题排查与解决方法
核心错误点
- 按钮命令绑定错误:提交按钮的
command参数传了字符串'submit',这不会触发对应函数,必须直接传入函数名submit - SQL语句字段与参数不匹配:INSERT语句声明要插入5个字段(Name,Class,Dob,Address,Phone),但仅传入2个参数,会导致SQL执行失败却无提示
- 异常捕获缺失:未对数据库操作添加异常处理,执行出错时无法收到报错信息,难以定位问题
修正后的完整代码
from tkinter import * import pymysql from tkinter import messagebox # 数据库连接 connection = pymysql.connect(host='localhost', user='root', passwd='', database='loginform') cursor = connection.cursor() root = Tk() root.geometry('400x400') # 定义输入变量 name = StringVar() class1 = StringVar() def submit(): try: # 只插入现有输入的字段(若需要录入其他字段,需对应添加输入控件并修改SQL) cursor.execute("INSERT INTO LOGIN1(Name, Class) VALUES(%s, %s)", (name.get(), class1.get())) connection.commit() messagebox.showinfo("提示", '数据录入成功') except Exception as e: connection.rollback() messagebox.showerror("错误", f"录入失败:{str(e)}") # 界面控件布局 Label(root, text="NAME").grid(row=1, column=1) Entry(root, textvariable=name).grid(row=1, column=2) Label(root, text="CLASS").grid(row=2, column=1) Entry(root, textvariable=class1).grid(row=2, column=2) # 修复命令绑定,直接传入函数名 Button(root, text="SUBMIT", command=submit, bg='gray', fg='white').grid(row=7, column=2) root.mainloop() # 程序退出时关闭数据库连接 cursor.close() connection.close()
额外优化建议
- 数据库连接建议嵌套
try-except块,避免连接失败直接导致程序崩溃 - 若需录入Dob、Address、Phone字段,需对应添加Label和Entry控件,并在
submit函数中获取对应变量值传入SQL语句 - 数据库密码等敏感信息不要硬编码,建议通过配置文件或环境变量读取
内容的提问来源于stack exchange,提问作者python fullstack
相关产品推荐
相关产品推荐

