skip to Main Content

I want to put ErrorMessageBox on this block of code. Like it shows that "The data has already existed".

Here is the block of code that saves to the database:

if (t1.get()==""  or t2.get()=="" or t3.get()=="" or t4.get()==""):
        messagebox.showinfo("Result","Please Complete the Provided Details!")

Here Connection to Database And Insertion

    else:
        databases = mysql.connector.connect(
        host ="localhost",
        user = "userdata",
        password = "",
        database = "facerecog"
        )

        cursors = databases.cursor()
        cursors.execute("SELECT * from record")
        result = cursors.fetchall()

Here Is the Code that Insert Data to Database

        id= t4.get()
        id = int(id)+1
        id
        sql = "INSERT INTO record(ids, names,course_year,positions) values(%s ,%s ,%s , %s)"
        val = (id, t1.get(), t2.get(), t3.get())
        cursors.execute(sql,val)
        databases.commit()

I would like to put the ErrorMessageBox if the data already exists.

In this block of code take photos. This code is connected to save database.

        face_classifier = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
        def face_cropped(img):
            gray = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
            faces = face_classifier.detectMultiScale(gray, 1.3, 5)
            # scaling factor = 1.3
            # minimum neighbor = 5
            if faces is ():
                return None
            for (x,y,w,h) in faces:
                    cropped_face = img[y:y+h, x:x+w]
            return cropped_face

        cap = cv2.VideoCapture(0)
        img_id = 0

        while True:
            ret, frame = cap.read()
            if face_cropped(frame) is not None:
                img_id+=1

                face = cv2.resize(face_cropped(frame), (200,200))
                face = cv2.cvtColor(face,cv2.COLOR_BGR2GRAY)

                file_name_path = "img/"+str (t1.get())+"." +str(id)+"."+str(img_id)+".jpg"


                cv2.imwrite(file_name_path, face)

                cv2.putText(face, str(img_id), (50,50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)

                cv2.imshow("Cropped face", face)

            if cv2.waitKey(1)==1 or int(img_id)==50:

                break

        cap.release()
        cv2.destroyAllWindows()

        messagebox.showinfo("Result","Saved Completed!")

2

Answers


  1. Look at this example –

    import tkinter as tk
    from tkinter import messagebox
    
    def error():
        messagebox.showerror('Error','There is an Error')
    
    root = tk.Tk()
    
    button1 = tk.Button(root,text='ERROR',command=error)
    button1.pack()
    
    root.mainloop()
    

    Reference – MessageBox

    messagebox.showinfo informs something in the message box.

    messagebox.showerror gives error message. You can implement this in your code

    It is another type of messagebox. You can have a look at more kinds of message box in the above link

    Edit – For your comment, if you want the error, you can do –

    messagebox.showerror('Heading of Error Message Box','raise errors.get_exception(packet) mysql.connector.errors.IntegrityError: 1062 (23000): Duplicate entry '4' for key 'PRIMARY'')
    

    Just replace the string with what you want.

    Login or Signup to reply.
  2. Here is an approach for you.

    You can try the insert to the database and if the data already exists it will throw an exception which you can handle with your desired message.

    import mysql.connector
    from mysql.connector import IntegrityError
    
    cnx = mysql.connector.connect(user='root', database='test', host='localhost', password='mypass')
    cursor = cnx.cursor()
    
    #This insert is only for duplication purposes since your id must be auto_incremental
    query = ("INSERT INTO students (id, name) values (3, 'andy')")
    
    try:
        cursor.execute(query)
        cnx.commit()
    except IntegrityError:
        print("Data already exists!")
    finally:
        cursor.close()
        cnx.close()
    

    The second approach as @furas suggested, first execute a select for retrieving your data if your result is not empty, then your data exists.

    import mysql.connector
    
    cnx = mysql.connector.connect(user='root', database='test', host='localhost', password='mypass')
    cursor = cnx.cursor()
    
    name = 'andy'
    query = f"SELECT * FROM students WHERE name = '{name}'"
    
    try:
        cursor.execute(query)
        res = cursor.fetchall()
        if res is not None:
            print(f"Data already exists: {res}")
        else:
            #Execute your insertion
            pass
    finally:
        cursor.close()
        cnx.close()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search