0

How can I code in a way that it tells my user that the input not available in the database?

Here is my code:

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)

My database have 2 columns:

username    Age
John        20
Amy         21

How can I code such that if the user inputs name as Jhn, And it cannot be found in the database table, then I would print wrong username

Currently if I input the name wrongly, it will still continue to the next code, which is printing the age. And it would print an empty age.

vt-0307
  • 63
  • 1
  • 7
  • Perhaps your function should return the `results` variable and then your existing code could examine it to see how many results were returned. – quamrana Jun 04 '20 at 16:20
  • Check this link: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – Thingamabobs Jun 04 '20 at 16:23

1 Answers1

1

If the name is not found, results will be an empty list. Your function can check for this, and in that case return None instead:

results = (execute_read_query (conn, query))
if not results:
    return None

Then in the calling code, you can check for a None return value:

age = sql_getage(name)
if age is None:
    print("Name not found")
else:
    print("Your age is", age)

Also, please change your query to set the name value with parameters instead of string formatting. You're leaving yourself wide open for an SQL injection attack.

John Gordon
  • 29,573
  • 7
  • 33
  • 58