0

我正在为我的部分课程制作一个登录系统,它会在其中查询数据库以查看数据是否正确。在我引入不在数据库中的登录名之前,它工作正常。无论如何,即使在 mycursor.fetchone() 给出不获取任何内容的错误之后,我也可以让 while 工作吗?

下面的代码是我遇到问题的子程序:

#the error message I'm receiving 
username, password = mycursor.fetchone()
TypeError: 'NoneType' object is not iterable

#the subroutine I'm having trouble with
def accept(self):
        conn = mysql.connector.connect(user, password, host, database)
        #create cursor between python and mysql
        mycursor = conn.cursor()

        query = """
            SELECT 
                username, password 
            FROM 
                UserInfo.User
            WHERE 
                username = %s AND password = %s
        """
        mycursor.execute(query, (self.textName.text(),self.textPass.text(), ))
        global username
        username, password = mycursor.fetchone()        
        #self.textName.text() and self.textPass.text() is the username and password entered by the user
        if username == self.textName.text() and password == self.textPass.text():
            self.GoToLogin()

        else:
            #the error message I want to display
            QtGui.QMessageBox.warning(
                self, 'Error', 'Username and password are incorrect')
4

1 回答 1

1

添加try except块并忽略未找到记录或找到多个记录时发生的异常。

try:
   #db call
except (SpecificException, AnotherException):
    pass

捕获特定异常比捕获所有异常要好,但在这种情况下,您可以只捕获全局Exception

此外,没有理由再次检查用户和密码是否相等,因为您已经将其作为查询的一部分传递。

于 2015-03-19T17:48:09.520 回答