I am trying to retrieve a password hash that i stored in my database. The problem is how i handle when the query is null.
In the case that I search for a user that exists the first print will print something but the in the second print that is inside the if statement it will output None
I don’t understand what is happening. It seems to me that the variable is loosing it’s value
db_password = c.execute("SELECT hashed FROM contas WHERE username=?", [username])
print(db_password.fetchone())
if(db_password.fetchone() != None):
print(db_password.fetchone())
hashed, = db_password.fetchone()
# Verify if passwords match
if ((bcrypt.checkpw(password.encode('utf8'), hashed) == False)):
print("Wrong credentials")
else:
print("User logged in successfully")
else:
print(db_password.fetchone())
print("User doesn't exist")
>Solution :
Each time you call db_password.fetchone()
it fetches the next row of results. But your query only returns one row.
The call in the if
statement fetches that row. Then the call in the print()
call tries to fetch the next row, but there isn’t another row, so it prints None
. Then the third call in the variable assignment tries to fetch the next row, but there still isn’t another row, so you get an error because you’re trying to assign None
in a tuple assignment.
You should fetch into a variable. Then you can test that and use it in the assignment.
row = db_password.fetchone()
if row:
print(row)
hashed = row[0]
...
else:
print("user doesn't exist")