求助:基于Sqlite3的Python登录程序无法识别正确用户名
登录程序数据库验证问题修复方案
问题根源分析
你的代码存在几个关键逻辑错误,导致无法正确验证用户名和密码:
- SQL语句错误:原代码把字符串字面量
"user1"和数据库字段username做比较,根本没有用到用户输入的变量;而且SQL中判断相等用=而非==,同时直接拼接变量存在SQL注入风险。 - 未获取查询结果:执行
c.execute()后没有调用fetchone()/fetchall()获取数据库返回的数据,反而拿SQL语句字符串和输入值对比,逻辑完全错误。 - 多余的commit操作:查询数据库不需要
conn.commit(),这个操作只用于增删改数据场景。 - 验证逻辑不合理:分开查询用户名和密码的方式效率低,且无法确保匹配的是同一个用户的信息。
修正后的代码
def loginpage(): bottom= Toplevel() bottom.title("SmartCards - Login") bottom.iconbitmap(r"C:\Users\Ethan\Documents\Comp NEA\Icon.ico") bottom.config(padx=50, pady=50, bg=BACKGROUND_COLOR) def submit2(): user1 = username1.get().strip() # 去除输入前后空格,避免误判 passwrd1 = password1.get().strip() # 参数化查询,同时匹配用户名和密码,避免SQL注入 sql = 'SELECT * FROM login WHERE username = ? AND password = ?' c.execute(sql, (user1, passwrd1)) # 获取匹配的第一条记录,无匹配则返回None matched_user = c.fetchone() if matched_user: messagebox.showinfo("Success","Login Successful!") else: # 不区分用户名/密码错误,防止恶意枚举用户名 messagebox.showwarning("Error","用户名或密码错误!") userbox = Label (bottom, text="Username:") userbox.grid(row=0, column=0) username1 = Entry(bottom) username1.insert(0,"") username1.grid(row=1, column=0) passbox1 = Label (bottom, text="Password:") passbox1.grid(row=2, column=0) # 密码框显示星号,保护隐私 password1 = Entry(bottom, show="*") password1.insert(0,"") password1.grid(row=3, column=0) submit = Button(bottom, text="Submit", command=submit2) submit.grid(row=4, column=0)
额外说明
- 代码中用
?作为占位符是SQLite的参数化写法,如果你用的是MySQL等其他数据库,需要替换为%s。 - 验证失败时不区分具体错误类型,是为了避免恶意用户通过错误提示枚举系统中存在的用户名,提升账号安全性。
内容的提问来源于stack exchange,提问作者Ethan Fuller
相关产品推荐
相关产品推荐

