Reputation: 4421
I am using python 2.7 with pyqt 4.10 and sqlite3
in my database, there is a foreign key between two table. I want to rise a GUI error to the user when he tries to delete the parent key that has values in the destination table associated with
the code :
deleted1 = self.listWidget.currentItem().text()
deleted = unicode(deleted1)
quit_title1 = 'تأكيد'
quit_title = quit_title1.decode('utf-8')
quit_msg1 = ' هل انت متأكد من مسح الفئة '
quit_msg = quit_msg1.decode('utf-8')
result = QtGui.QMessageBox.critical(Dialog, quit_title, quit_msg, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if result == QtGui.QMessageBox.Yes:
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("PRAGMA foreign_keys = 1")
c.execute("DELETE FROM categories WHERE category_name = (?)", (deleted, ))
conn.commit()
conn.close()
its gives back the error :
Traceback (most recent call last):
File "C:\python\townoftechwarehouse\edit_category.py", line 102, in deleteing
c.execute("DELETE FROM categories WHERE category_name = (?)", (deleted, ))
sqlite3.IntegrityError: FOREIGN KEY constraint failed
This error doesn't terminate the program , but it totally do nothing in the UI and i want the user to know that he is enable to delete it because there is connections with it in the database
Upvotes: 0
Views: 57
Reputation: 121
Just wrap it in try/except and catch sqlite3.IntegrityError. Then you can do pretty much whatever if that error occur.
(Since you are initiating the database and doing everything in on go here i would suggest a bit of refactoring into several functions..)
But here is an example, ive skipped to GUI parts.
deleted1 = self.listWidget.currentItem().text()
deleted = unicode(deleted1)
quit_title1 = 'تأكيد'
quit_title = quit_title1.decode('utf-8')
quit_msg1 = ' هل انت متأكد من مسح الفئة '
quit_msg = quit_msg1.decode('utf-8')
result = QtGui.QMessageBox.critical(Dialog, quit_title, quit_msg, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if result == QtGui.QMessageBox.Yes:
try:
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("PRAGMA foreign_keys = 1")
c.execute("DELETE FROM categories WHERE category_name = (?)", (deleted, ))
conn.commit()
conn.close()
except sqlite3.IntegrityError:
# Do whatever
Upvotes: 1