python - 显示消息框数据已存在
问题描述
我想把 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!")
解决方案
这是适合您的方法。
您可以尝试插入数据库,如果数据已经存在,它将引发异常,您可以使用所需的消息处理该异常。
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()
推荐阅读
- algorithm - 第一个除以所有数字的数字 (1,2,...,100)
- android - NullPointerException 与导航组件的参数与 defaultValue
- asp.net-core - ASP.NET CORE 中基于角色的静态内容访问
- php - 执行查询获取数组而不是值
- java - 面向对象将项目添加到 arrayList
- python - 如何在 Tensorflow 中获取 CUDA/GPU/设备指针?
- python - 获取一个数除以另一个数和余数的所有时间的列表
- django - 自定义刷新 JWT 令牌 Django 中的错误
- python - 如何在 python 中将状态变量保留在两个级别?
- javascript - 如何使用popper js相对于主体而不是父级定位下拉列表