为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法告诉用户输入错误?

有没有办法告诉用户输入错误?

摇曳的蔷薇 2022-12-27 09:59:21
我如何以一种方式编码,告诉我的用户输入在数据库中不可用?这是我的代码:def sql_getage(name):    query = """\        select age from store        where name = '{}'        """.format(name)    results = (execute_read_query (conn, query))    for i in results:        theresult = str(i[0])    return (theresult)name = input("Please input your username")age = sql_getage(name)print("Your age is", age)我的数据库有 2 列:username    AgeJohn        20Amy         21我如何编写代码,如果用户输入名称为 Jhn,并且在数据库表中找不到它,那么我会打印wrong username目前如果我输入错误的名字,它仍然会继续下一个代码,打印年龄。它会打印一个空的年龄。
查看完整描述

1 回答

?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

如果找不到该名称,results将是一个空列表。您的函数可以检查这一点,在这种情况下返回None:


results = (execute_read_query (conn, query))

if not results:

    return None

然后在调用代码中,您可以检查None返回值:


age = sql_getage(name)

if age is None:

    print("Name not found")

else:

    print("Your age is", age)

另外,请更改您的查询以使用参数而不是字符串格式来设置名称值。您正在为 SQL 注入攻击敞开大门。


查看完整回答
反对 回复 2022-12-27
  • 1 回答
  • 0 关注
  • 106 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号