Python with MYSQL - ERROR: 'Nonetype' Object is not subscriptable

Asked

Viewed 180 times

-1

I am trying to practice creating a small program with LOGIN SCREEN. This program has access to a MYSQL database and I want to VALIDATE the login data to allow entry.

I’m trying to learn on my own and having a lot of difficulties. It happens that when I try to enter with a user that already exists in the bank, but error the password, the program works normal. However, when I try a LOGIN that is not in the bank, the program displays this error. I could not find solution yet.

login_user = tela_login.lineEdit.text()
senha_user = tela_login.lineEdit_2.text()

cursor = banco.cursor()
cursor.execute(
    "SELECT senha FROM quadro_funcionarios WHERE login = '{}'".format(login_user))
senha_banco = cursor.fetchone()

if senha_user == senha_banco[0]:
    tela_login.close()
    menu_principal.show()

The error generated is this:

 22     senha_banco = cursor.fetchone()
 23 
 24     if senha_user == senha_banco[0]: #Erro nesta linha aqui.
 25         tela_login.close()
 26         menu_principal.show()

Typeerror: 'Nonetype' Object is not subscriptable

I’m looking everywhere, how to solve, but I don’t understand the mistake.

  • 1

    probably the value of pass_bank is None.

  • You can edit the question to include your query, and better explain the problem.

  • Thank you. I just did that.

  • You are looking for a user that DOES NOT EXIST in your bank. You have to check if something comes there. Probably comes a None as @Danizavtz commented. Ai tu ta trying to access a None[0], makes sense?

1 answer

1


The error happens when you are accessing the index of an object that is None.

spam = None

print(spam[0])
# TypeError: 'NoneType' object is not subscriptable

Whereas in your code there is only senha_banco[0], then senha_banco is None.

By checking the documentation of fetchone you have:

This method retrieves the next Row of a query result set and Returns a single Quence, or None if no more Rows are available.

That is, he can return None when there is no record to be returned. In your case, everything indicates that the log with the login entered has not been found.

You can validate this with the rowcount:

if cursor.rowcount == 0:
  raise Exception(f'Nenhum registro encontrado com o login {login_user}')

But it will be interesting for you to debug the code and make sure that the record exists in the database.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.