How to check if a data exists in the table before inserting Mysql + Python

Asked

Viewed 424 times

0

I’m trying to verify if a data already exists in the database before entering.

My code is like this:

nome = input("Insira seu usuario: ")
seleciona = "SELECT nomes FROM slogin"
cursor.execute(seleciona)
resultado = cursor.fetchall()
if nome in resultado
    print('Usuario Já Cadastrado')
else:
    print('Cadastro realizado')

But it doesn’t work. How could I fix, what’s wrong with the code?

1 answer

-1


Imagine that you have a large company that uses your system and you have as a result of SELECT nomes FROM slogin more than 100,000 registrations. Imagine that each of the 100,000 users logs in at the same time. You will soon notice that your system will paralyze, because you will not only do a search that returns 100 thousand you will also have to go through these 100 thousand records to check if it exists.

So what’s the option?

The best thing here is to use the database itself to do this research: You tell Mysql: Select the Nomes from the table Slogin where Name is equal to the given Name (entered in the input)

The database with its native search engine will be much faster in finding the answer than you bring all the records and search for yourself.

Here is a code suggestion:

nome = input("Insira seu usuario: ")
seleciona = "SELECT nomes FROM slogin WHERE nomes ='{}'".format(nome)
cursor.execute(seleciona)
resultado = cursor.fetchall()
if len(resultado)!=0:  #Verifica se o retorno contém alguma linha
    print('Usuario Já Cadastrado')
else:
    print('Cadastro realizado')
  • 1

    "database with its native search engine will be much faster in finding the answer", not necessarily, because depending on how the table was defined this query may result in a FULL SCAN and take up to more than the original query (what weighs in the original is the data transfer, not the query time). Not to mention that doing a SELECT before INSERT generates a running condition in the application. The ideal is to set the column as UNIQUE and try to insert straight. If it already exists, it will give error.

  • Correct. I tried to give a simple answer, without changing much the initial code, as I saw that the user is starting. Make the insertion generates a Key Violation (or Contraint) error and treat this error as "Existing User", although correct, seems to me a little advanced.

Browser other questions tagged

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