我如何以一種方式編碼,告訴我的用戶輸入在數據庫中不可用?這是我的代碼: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目前如果我輸入錯誤的名字,它仍然會繼續(xù)下一個代碼,打印年齡。它會打印一個空的年齡。
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 注入攻擊敞開大門。
添加回答
舉報
0/150
提交
取消