我如何以一種方式編碼,告訴我的用戶輸入在數(shù)據(jù)庫(kù)中不可用?這是我的代碼: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)我的數(shù)據(jù)庫(kù)有 2 列:username AgeJohn 20Amy 21我如何編寫代碼,如果用戶輸入名稱為 Jhn,并且在數(shù)據(jù)庫(kù)表中找不到它,那么我會(huì)打印wrong username目前如果我輸入錯(cuò)誤的名字,它仍然會(huì)繼續(xù)下一個(gè)代碼,打印年齡。它會(huì)打印一個(gè)空的年齡。
1 回答
梵蒂岡之花
TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果找不到該名稱,results將是一個(gè)空列表。您的函數(shù)可以檢查這一點(diǎn),在這種情況下返回None:
results = (execute_read_query (conn, query))
if not results:
return None
然后在調(diào)用代碼中,您可以檢查None返回值:
age = sql_getage(name)
if age is None:
print("Name not found")
else:
print("Your age is", age)
另外,請(qǐng)更改您的查詢以使用參數(shù)而不是字符串格式來設(shè)置名稱值。您正在為 SQL 注入攻擊敞開大門。
添加回答
舉報(bào)
0/150
提交
取消
