python - 有没有办法告诉用户输入错误?
问题描述
如何以一种告诉我的用户数据库中不可用的输入的方式进行编码?
这是我的代码:
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 Age
John 20
Amy 21
我该如何编码,如果用户输入名称为
Jhn
,并且在数据库表中找不到它,那么我会打印wrong username
目前如果我输入错误的名字,它仍然会继续下一个代码,即打印年龄。它会打印一个空的年龄。
解决方案
如果未找到名称,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 注入攻击敞开大门。
推荐阅读
- reactjs - 错误:使用导航器的无效挂钩调用 React native
- python - 仅当元素不同时,才将多行合并为单行,并在单元格中使用列表
- reactjs - Toast UI 日历可以与 Google 日历集成吗?如果是这样,是否有任何使用打字稿可用的示例
- c - 避免在两个屏幕之间打开窗口
- python - pandas.dataframe 等效于 Pandas.read_csv 转换器?
- android-studio - 始终使文本输入布局中的前缀文本像提示一样可见
- plsql - REPLACE 在 plsql 过程中不起作用
- javascript - 单选按钮答案出现在
- omnet++ - 我们使用哪些工具在 VANEt 中实现 Sybil 攻击模拟
- wordpress - 如何通过从另一个页面单击按钮将预制文本添加到表单?WordPress 元素