Python连接MySQL项目中option==4查询存在数据却提示不存在
排查Python连接MySQL客户查询功能的异常原因
核心问题分析
在option==4的客户查询代码块中,存在两个关键错误导致查询失效:
1. 游标结果集被重复读取耗尽
执行查询语句后,你先调用c = c1.fetchall()将所有查询结果读取到变量c中,此时MySQL游标已经移动到结果集末尾。紧接着再次调用c1.fetchall()尝试读取数据,这会返回空列表,导致变量b为空。
2. 错误的条件判断逻辑
你用空列表b和整数类型的accnum做相等判断(b == accnum),这种类型不匹配的判断永远不会成立,所以必然进入else分支,提示客户信息不存在。
额外优化点:account_number是数值类型,使用like运算符无意义,直接用=更合理;同时直接拼接SQL语句存在SQL注入风险,建议使用参数化查询。
修正后的代码
将option==4的代码替换为以下内容:
if option==4: accnum=int(input("Enter the Customer's Account Number :")) print("Customer Account Number, Customer name, Phone Numbers Are Given Below") print() # 使用参数化查询避免注入,同时用=代替like匹配数值类型字段 c1.execute("select account_number, patient_name, phone_number from customers_details where account_number = %s", (accnum,)) c = c1.fetchall() # 直接判断结果集是否为空即可确认是否存在数据 if c: for x in c: print("Account Number : " ,x[0]) print("Name : ",x[1]) print("Mobile Number : ",x[2]) print() else: print("Customer Details Dont exist") print("Create A New Account")
修正说明
- 移除重复读取游标的操作,直接通过判断结果集
c是否为空来确认客户数据是否存在 - 使用参数化查询(
%s作为占位符),避免SQL注入风险,同时让代码更安全规范 - 将
like替换为=,符合数值类型字段的查询逻辑
内容的提问来源于stack exchange,提问作者Preetham. Ch
相关产品推荐
相关产品推荐

