简体   繁体   中英

Python variable loses value when passed to a if statement

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")

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")

Calling fetchone() will move the cursor to the next row each time and return None if there are no rows available (see documentation here ). If you want to just check the one password, store the result of the fetchone call in a variable and use it for future comparisons/printing, ie

password = db_password.fetchone()
print(password)
if password is not None:
    print(password) # If password is not None, this will print the same thing as the previous print call
    ...
else:
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM