Python Forum
[Tkinter] Error verify data in database
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Error verify data in database
#1
Hello good,

I have a problem verifying a login. For example, I have 3 records in the database and only 1 user and password are valid, the other two are 2, it always throws me to the "ELIF" that the data is incorrect.

what can be due to that?

I have
user: 1
password: 1

user: 2
password: 2

user: 3
password: 3

Well, of these 3 users, only user 3 fits me well, the other 2 users send me to the "elif" of incorrect data, when everything is fine.

self.connection2 = connect_to_database()
       self.cursor2 = self.connection2.cursor()
       # Ejemplo: Ejecutar una consulta para obtener datos
       self.cursor2.execute("SELECT nombre,password FROM usuarios")
       self.data2 = self.cursor2.fetchall()
       #messagebox.showwarning("Advertencia", self.data2)
       # Cerrar el cursor y la conexión

       for self.fila in self.data2:
           self.v_email = self.fila[0]
           self.v_password = self.fila[1]

       self.cursor2.close()
       self.connection2.close()

       if self.entry_email.get() == "" or self.entry_password.get() == "":
           self.dialogo = tk.Toplevel()
           self.dialogo.title("ERROR")
           self.dialogo.geometry("300x50")
           self.dialogo.resizable(0,0)

           self.wtotal2 = self.dialogo.winfo_screenwidth()
           self.htotal2 = self.dialogo.winfo_screenheight()

           self.wventana2 = 300
           self.hventana2 = 100

           self.pwidth2 = round(self.wtotal2/2-self.wventana2/2)
           self.pheight2 = round(self.htotal2/2-self.hventana2/2)

           self.dialogo.geometry(str(self.wventana2)+"x"+str(self.hventana2)+"+"+str(self.pwidth2)+"+"+str(self.pheight2))
           self.etiqueta = tk.Label(self.dialogo, text="Rellena todos los campos.", padx=10, pady=10)
           self.etiqueta.pack()

           self.image_boton_vale = Image.open("src/boton_vale.png")
           self.photo_boton_vale = ImageTk.PhotoImage(self.image_boton_vale)

           self.boton_vale = tk.Button(self.dialogo, image=self.photo_boton_vale, command=self.cerrar_dialogo_vale)
           self.boton_vale.pack(pady=5)
           self.boton_vale.place(x=86, y=50, width=128, height=31)

       elif self.entry_email.get() == self.v_email and self.entry_password.get() == self.v_password:
           self.app.root.destroy()
           self.ventana_menu = Menus(self)
       else:
           self.app.root.destroy()
           messagebox.showwarning("Advertencia", "Los datos introducidos son incorrectos.")
What could cause this error?
Reply
#2
I think your logic is wrong. You retrieve all the email and passwords from the database, but you thow all of them away except for the last.
       self.cursor2.execute("SELECT nombre,password FROM usuarios")
       self.data2 = self.cursor2.fetchall()
       for self.fila in self.data2:
           self.v_email = self.fila[0]
           self.v_password = self.fila[1]
v_email and v_password are from the last row in usuarios.

Using the last email and password you do your checking.
       if self.entry_email.get() == "" or self.entry_password.get() == "":
           # Make dialog
       elif self.entry_email.get() == self.v_email and self.entry_password.get() == self.v_password:
           self.app.root.destroy()
           self.ventana_menu = Menus(self)
       else:
           self.app.root.destroy()
           messagebox.showwarning("Advertencia", "Los datos introducidos son incorrectos.")
Correcting this problem using your approach is challenging. You would have to check every email until you found a match, then you would have to check the corresponding password. A much easier approach is have the database do all the work.

In the example below, the database looks up the password for the provided username. If the username is not found, the query returns None. If a password is retuned, the program checks it against the expected password.
import sqlite3 as sql
import pandas as pd


db_file = "passwords.db"


def lookup_password(username):
    db = sql.connect(db_file)
    # Create password table if none exists.  This is for demonstration purposes only.
    try:
        db.execute("SELECT * from passwords")
    except sql.OperationalError:
        # Query failed.  Create table with entries from OP.
        df = pd.DataFrame({
            "name": ["user 1", "user 2", "user 3"],
            "password": ["password 1", "password 2", "password 3"]
        })
        df.to_sql("passwords", db, df)

    # Lookup password for username.  Will get None if the username is not in the table.
    password = db.execute("SELECT password FROM passwords WHERE name=?", (username,)).fetchone()
    db.close()
    return password[0] if password else None


def check_password(username, password):
    # Check if the password is valid.  
    pwd = lookup_password(username)
    if pwd is None:  # the username was invalid.
        print(f"There is no user '{username}'",)
    elif pwd != password:  # the password doesn't match.
        print(f"Entered password '{password}' does not match '{pwd}' for user '{username}'")
    else:
        print(f"Password '{password}' is valid for user '{username}'")


check_password("user 1", "password 1")
check_password("user 2", "password 3")
check_password("user 4", "password 4")
It should be easy to modify your program to use similar logic.
TomasSanchexx likes this post
Reply
#3
(Aug-10-2023, 08:32 PM)deanhystad Wrote: I think your logic is wrong. You retrieve all the email and passwords from the database, but you thow all of them away except for the last.
       self.cursor2.execute("SELECT nombre,password FROM usuarios")
       self.data2 = self.cursor2.fetchall()
       for self.fila in self.data2:
           self.v_email = self.fila[0]
           self.v_password = self.fila[1]
v_email and v_password are from the last row in usuarios.

Using the last email and password you do your checking.
       if self.entry_email.get() == "" or self.entry_password.get() == "":
           # Make dialog
       elif self.entry_email.get() == self.v_email and self.entry_password.get() == self.v_password:
           self.app.root.destroy()
           self.ventana_menu = Menus(self)
       else:
           self.app.root.destroy()
           messagebox.showwarning("Advertencia", "Los datos introducidos son incorrectos.")
Correcting this problem using your approach is challenging. You would have to check every email until you found a match, then you would have to check the corresponding password. A much easier approach is have the database do all the work.

In the example below, the database looks up the password for the provided username. If the username is not found, the query returns None. If a password is retuned, the program checks it against the expected password.
import sqlite3 as sql
import pandas as pd


db_file = "passwords.db"


def lookup_password(username):
    db = sql.connect(db_file)
    # Create password table if none exists.  This is for demonstration purposes only.
    try:
        db.execute("SELECT * from passwords")
    except sql.OperationalError:
        # Query failed.  Create table with entries from OP.
        df = pd.DataFrame({
            "name": ["user 1", "user 2", "user 3"],
            "password": ["password 1", "password 2", "password 3"]
        })
        df.to_sql("passwords", db, df)

    # Lookup password for username.  Will get None if the username is not in the table.
    password = db.execute("SELECT password FROM passwords WHERE name=?", (username,)).fetchone()
    db.close()
    return password[0] if password else None


def check_password(username, password):
    # Check if the password is valid.  
    pwd = lookup_password(username)
    if pwd is None:  # the username was invalid.
        print(f"There is no user '{username}'",)
    elif pwd != password:  # the password doesn't match.
        print(f"Entered password '{password}' does not match '{pwd}' for user '{username}'")
    else:
        print(f"Password '{password}' is valid for user '{username}'")


check_password("user 1", "password 1")
check_password("user 2", "password 3")
check_password("user 4", "password 4")
It should be easy to modify your program to use similar logic.

Thank you very much, I have already solved it.

self.consulta = "SELECT * FROM usuarios WHERE nombre = %s AND password = %s"
        #self.cursor2.execute("SELECT nombre,password FROM usuarios")
        self.cursor2.execute(self.consulta, (self.use, self.pas))
        self.data2 = self.cursor2.fetchall()
elif self.data2:
            self.app.root.destroy()
            VariablesGlobales.variable_global1 = self.use
            self.ventana_menu = Menus(self)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PyQt5 form not displaying my data from SQLite3 Database Linuxdesire 2 5,000 Jan-10-2023, 09:51 PM
Last Post: gradlon93
Question [Tkinter] data enterred through gui is not storing in sqlite3 database Hilal 21 7,617 Dec-15-2021, 08:48 PM
Last Post: Hilal
  Button to add data to database and listbox SalsaBeanDip 1 2,887 Dec-06-2020, 10:13 PM
Last Post: Larz60+
  [Tkinter] Displaying Data from a database and run a function when clicked? PythonNPC 1 2,074 Mar-11-2020, 08:16 PM
Last Post: Larz60+
  Database Submit Entry Syntax Error Melford 27 7,820 Jan-27-2020, 04:20 PM
Last Post: Denni

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020