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

Python数据库登录脚本else分支不执行问题求助

问题修复:登录脚本中无匹配账号时else分支不执行的问题

问题描述

我想编写一个从数据库获取账号信息的登录页面脚本,但输入的用户名和密码在数据库中不存在时,else分支根本不会执行,该怎么修复?

原代码

def logindb():
    print ("=="*15+"\nPlease insert your username and password.")
    username = input ("Username : ")
    password = input ("Password : ")
    cursor.execute(f"SELECT * FROM data WHERE username='{username}' and password='{password}'")
    result = cursor.fetchall()
    for i in result:
        if (i[0]) == username and (i[1]) == password:
            print ("=="*15+"\n\tLogin Success.\n"+"=="*15)
        else:
            print ("=="*15+"\nUsername or password is wrong.\n"+"=="*15)

问题原因

你的代码逻辑存在两个核心问题:

  • 当数据库中没有匹配的账号密码时,cursor.fetchall()会返回空列表,for i in result循环根本不会启动,自然走不到else分支
  • 循环里的账号密码判断完全多余:你的SQL语句已经限定了username='{username}' and password='{password}',能查到的记录必然是匹配的

另外,用f-string直接拼接用户输入到SQL语句里,存在SQL注入风险,这是严重的安全漏洞,必须修正。

修复后的代码

def logindb():
    print("=="*15 + "\n请输入用户名和密码。")
    username = input("用户名: ")
    password = input("密码: ")
    # 使用参数化查询避免SQL注入
    cursor.execute("SELECT * FROM data WHERE username=%s and password=%s", (username, password))
    result = cursor.fetchall()
    
    if result:
        # 查询到结果=账号密码匹配
        print("=="*15 + "\n\t登录成功。\n" + "=="*15)
    else:
        # 无结果=账号或密码错误
        print("=="*15 + "\n用户名或密码错误。\n" + "=="*15)

修复说明

  1. 直接判断查询结果:检查result是否非空,为空直接触发错误提示,解决了原代码无匹配时不执行else的问题
  2. 移除多余循环判断:利用SQL的过滤逻辑,只要有查询结果就说明登录成功,无需二次校验
  3. 替换为参数化查询:彻底杜绝SQL注入风险,这是数据库操作的标准安全规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:15:29