每当我运行此代码,并且密码不匹配时,应用程序就会崩溃我如何解决它?

问题描述

这是我现在拥有的代码,我这样做是为了检查密码和确认的密码是否匹配,然后将该值存储到UpdatedPassword中以对其进行哈希处理并存储在我的数据库中。

import MysqL.connector import hashlib

cnx = MysqL.connector.connect(user='root',password='!Joshua1',host='127.0.0.1',database='passwordhashtest')

cursor = cnx.cursor()

Email= input("enter your email address") 
Password=input("enter your password") 
ConfirmPassword=input("confirm your password")

if(Password==ConfirmPassword):
    UpdatedPassword=ConfirmPassword
else:
    print("passwords dont match")
    HashedPassword=hashlib.md5(UpdatedPassword.encode('utf8')).hexdigest()

sqlFormula= "INSERT INTO password2 (Email,Password) VALUES (%s,%s)"

values=(Email,HashedPassword)

cursor.execute(sqlFormula,values)

cnx.commit()

事情崩溃了,这是我得到的错误

'UpdatedPassword' is not defined

我尝试将UpdatedPassword值分配给'',然后使sql列NOT NULL,但是它仍然存储了该信息。

我该如何解决

解决方法

您正在if块中创建UpdatedPassword,因此在该块之外无法访问它。

在if块之前定义UpdatedPassword

这是由于scope of that variable

更新:尝试通过以下方式

import mysql.connector import hashlib

cnx = mysql.connector.connect(user='root',password='!Joshua1',host='127.0.0.1',database='passwordhashtest')

cursor = cnx.cursor()

Email= input("enter your email address") 
Password=input("enter your password") 
ConfirmPassword=input("confirm your password")

if(Password==ConfirmPassword):
    HashedPassword=hashlib.md5(Password.encode('utf8')).hexdigest()
    sqlFormula= "INSERT INTO password2 (Email,Password) VALUES (%s,%s)"
    values=(Email,HashedPassword)
    cursor.execute(sqlFormula,values)
    cnx.commit()
else:
    print("passwords dont match")
    
,

请尝试在if语句之外定义UpdatedPassword,并在HashedPassword之外定义,因为该数据是在特定范围内定义的,因此可能不会延续到整个脚本中。如果您在范围之外进行定义,则它将应用于所有内容。