Doubt about finding information in the database

Asked

Viewed 56 times

-2

I’m trying to make a simple system of login, would like the system to check the logins that are already registered in the database, so that you have no more than one equal registered. I am using the Sqlite3 as a bank.

I’m doing like this.

import sqlite3

banco = sqlite3.connect('sistema_cadastro.db')
cursor = banco.cursor()
cursor.execute("SELECT login FROM usuarios")
banco.commit()
tabela = cursor.fetchall()
print(tabela)
login = [tabela]
str(login)
if 'bruno' in login:
    print('Encontrou! (: ')
else:
    print('Não encontrou ): ')
banco.close()

I’m making a select login in the user table and giving a print
The print is showing the following information:

[('adm',), ('bruno',), ('teste',)]

Then I put a if looking for 'Bruno' in the login list. But he doesn’t, and always plays for the else.
I would like to see a way for him to find the variable 'Bruno' in the login list'.

  • 1

    Do this in SQL, for example(I don’t know your data structure but), SELECT login FROM usuarios where nome="bruno"

1 answer

-2

The return of a database consists of a list of tuples, that is, you must access the list, right after the contents of the tuples and search for the necessary information. With only an "IF " your code will be using only the first list as parameter. With this, I advise you to use a "FOR" loop to go through all the contents of the list (the tuples) and finally an "IF IN" in the tuples so that the program can access the strings and, when finding the desired information, it can execute the true case code. I still hint to use the Index functions (returns the Index of a collection value) and Len(returns the collection size) to print the negation only when the program completes the search in the entire list, plus a break at the end of the IF execution to exit the FOR loop when the searched value is found. Attached an example so you can better understand the explanation:

b = [('bruno',), ('rodrigo',), ('joana',)]

for x in b:
        if 'rodrigo' in x:
            print('Nome encontrado :)')
            break
        elif b.index(x) == len(b) -1:
            print('Nome não encontrado :(')

Browser other questions tagged

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