Bobby
Bobby

Reputation: 41

cur.fetchone()[0] is all of a sudden a Nonetype

Im making a login system as a data base Im using SQLite.

def loginfunction(self):
    user = self.emailfield.text()
    password = self.passwordfield.text()

    if len(user)==0 or len(password)==0:
        self.error.setText("Please input all fields.")

    else:
        conn = sqlite3.connect("shop_data.db")
        cur = conn.cursor()
        query = 'SELECT password FROM login_info WHERE username =\''+user+"\'"
        cur.execute(query)
        result_pass = cur.fetchone()[0]
        if result_pass == password:
            print("Successfully logged in.")
            self.error.setText("")
        else:
            self.error.setText("Invalid username or password")

When I run it if the password does not match with the username from the data base it works but if I type a wrong username the app closes and prints out this

main.py", line 38, in loginfunction
result_pass = cur.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable

Here is what SQLite log says + what the data base looks like data base

Upvotes: 0

Views: 391

Answers (1)

Daweo
Daweo

Reputation: 36590

fetchone does

Fetches the next row of a query result set, returning a single sequence, or None when no more data is available.

For any

'SELECT password FROM login_info WHERE username =\''+user+"\'"

there is not matching row in data if user provided username not present in username column. You should do something like

query_result = cur.fetchone()
if result_pass is None:
    print("Username with given name is not known")
    # action to undertake in such case
result_pass = query_result[0]

then continue as earlier

Upvotes: 1

Related Questions