Python GUI登录功能:输入正确密码仍提示错误的排查求助
问题原因与解决方案
- 核心问题:
cursor.fetchone()返回的是元组类型(例如查询到密码为123456时,r的值是('123456',)),你直接将其与字符串类型的输入密码n2比较,必然不相等,因此触发错误提示。 - 修复代码:修改
login_submit函数中的密码判断逻辑,提取元组中的第一个元素再做比较:
def login_submit(): n1 = en_username.get() n2 = en_password.get() # 改用参数化查询避免SQL注入风险 q1 = "select password from data where username = %s" cursor.execute(q1, (n1,)) r = cursor.fetchone() if r: # 提取元组中的密码字符串进行比较 if r[0] == n2: messagebox.showinfo(title="Logged in", message="Logged in Succesfully") else: messagebox.showerror(title="Failed to login", message="Wrong password") else: messagebox.showerror(title="Error", message="No such account exists") firstwindow()
额外优化建议
- 避免SQL注入:原代码使用
format拼接SQL语句存在注入风险,改用参数化查询(如上述代码中的%s占位符),将参数单独传入execute方法,能有效避免该问题。 - 简化代码:无需给
messagebox的返回值赋值(比如success = messagebox.showinfo(...)),直接调用即可。
内容的提问来源于stack exchange,提问作者Krishan Kumar
相关产品推荐
相关产品推荐

