简体   繁体   English

Python 变量在传递给 if 语句时会丢失值

[英]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在我搜索存在的用户的情况下,第一个 print将打印一些东西,但在 if 语句内的第二个 print中它将输出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.每次调用db_password.fetchone()时,它都会获取下一行结果。 But your query only returns one row.但是您的查询只返回一行。

The call in the if statement fetches that row. if语句中的调用获取该行。 Then the call in the print() call tries to fetch the next row, but there isn't another row, so it prints None .然后print()调用中的调用尝试获取下一行,但没有另一行,所以它打印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.然后变量赋值中的第三个调用尝试获取下一行,但仍然没有另一行,所以你得到一个错误,因为你试图在一个元组赋值中分配None

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 ).每次调用 fetchone() 都会将光标移动到下一行,如果没有可用的行则返回 None(请参阅此处的文档)。 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如果您只想检查一个密码,请将 fetchone 调用的结果存储在一个变量中,并将其用于将来的比较/打印,即

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:
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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