【问题标题】:Show Message Box data already exist显示消息框数据已存在
【发布时间】:2021-11-18 04:27:27
【问题描述】:

我想把 ErrorMessageBox 放在这个代码块上。就像它表明“数据已经存在”。

这是保存到数据库的代码块:

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

这里连接到数据库和插入

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

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

这是向数据库插入数据的代码

        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()

如果数据已经存在,我想放 ErrorMessageBox。

在这段代码中拍照。此代码连接保存数据库。

        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!")

【问题讨论】:

  • 您究竟需要在哪里执行验证?请您在您的代码中添加注释以了解如何为您提供帮助?
  • 完成@sirandy 编辑
  • 在INSERT 之前,您可能需要执行SELECT ... new_values 来检查数据库中是否已有此数据。
  • 如果它在消息框中显示代码错误怎么办?我的意思是它弹出消息框什么错误
  • 你已经说出了你想要的,但你还没有提出任何问题。您需要帮助解决问题的哪一部分?

标签: python tkinter phpmyadmin localhost


【解决方案1】:

这里有一个适合你的方法。

您可以尝试插入数据库,如果数据已经存在,它将抛出一个异常,您可以使用所需的消息进行处理。

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()

@furas 建议的第二种方法,如果您的结果不为空,则首先执行选择以检索您的数据,然后您的数据存在。

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()

【讨论】:

    【解决方案2】:

    看看这个例子-

    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()
    

    参考 - MessageBox

    messagebox.showinfo 通知消息框中的某些内容。

    messagebox.showerror 给出错误信息。你可以在你的代码中实现它

    这是另一种类型的消息框。您可以在上面的链接中查看更多种类的消息框

    编辑 - 对于您的评论,如果您想要错误,您可以这样做 -

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

    只需将字符串替换为您想要的。

    【讨论】:

    • raise errors.get_exception(packet) mysql.connector.errors.IntegrityError: 1062 (23000): Duplicate entry '4' for key 'PRIMARY' 这在我的 IDE 中显示错误,我该如何显示它喜欢消息框
    • 你能看到“有一个错误”字符串吗,用你的错误替换它。
    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多