锋哥原创的PyQt6图书管理系统视频教程:
PyQt6图书管理系统视频教程 Python桌面开发 Python入门级项目实战 (无废话版) 火爆连载更新中~_哔哩哔哩_bilibiliPyQt6图书管理系统视频教程 Python桌面开发 Python入门级项目实战 (无废话版) 火爆连载更新中~共计24条视频,包括:PyQt6图书管理系统视频教程 Python桌面开发 Python入门级项目实战 (无废话版) 火爆连载更新中~、第2讲 登录功能UI设计实现、第3讲 数据库操作工具包dbUtil.py封装等,UP主更多精彩视频,请关注UP账号。https://www.bilibili.com/video/BV18t4y1R7Qp/首先bookTypeDao里,写下delete方法:
def delete(id):
"""
图书类别删除
:param id: 编号
:return: 返回执行的记录条数
"""
con = None
try:
con = dbUtil.getCon()
cursor = con.cursor()
cursor.execute(f"delete from t_booktype where id={id}")
return cursor.rowcount
except Exception as e:
print(e)
con.rollback()
return 0
finally:
dbUtil.closeCon(con)
bookTypeManage.py里的Ui_Form,我们加下resetForm方法,删除成功后,要重置下表单
def resetForm(self):
self.idInput.setText("")
self.bookTypeNameInput.setText("")
self.bookTypeDescInput.setPlainText("")
再定义delete方法:
def delete(self):
"""
删除记录
:return:
"""
id = self.idInput.text()
if id.strip() == "":
QMessageBox.information(None, '系统提示', '请选中您需要删除的那行数据!')
return
reply = QMessageBox.question(self, "系统提示", "您确定要删除这条记录吗?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No)
if reply == QMessageBox.StandardButton.Yes:
if bookTypeDao.delete(id) > 0:
QMessageBox.information(None, '系统提示', '删除成功!')
self.initTable()
self.resetForm()
else:
QMessageBox.warning(None, '系统提示', '删除失败!')
删除按钮绑定事件:
# 删除按钮事件
self.deleteBtn.clicked.connect(self.delete)
我们测试删除最后一个数据没问题,但是,删除第一个数据报错了。
具体的报错信息:
1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`db_book2`.`t_book`, CONSTRAINT `t_book_ibfk_1` FOREIGN KEY (`bookTypeId`) REFERENCES `t_booktype` (`id`))')
意思是删除的数据,外键关联的数据还引用着,不能删除。
白话文,就是要删除的图书类别还关联着图书,所以删除报错。
我们企业级开发,加下判断即可。删除前,判断下该类别下是否存在图书,假如存在,就给下用户界面搞一个提示即可。
完善方案如下:先新建一个bookDao.py
新建一个countByTypeId方法,判断图书类别下是否有图书数量:
def countByTypeId(typeId):
"""
根据图书类别ID查询图书数量
:param typeId:
:return:
"""
con = None
try:
con = dbUtil.getCon()
cursor = con.cursor()
sql = "SELECT count(*) as total from t_book where bookTypeId=" + str(typeId)
cursor.execute(sql)
return cursor.fetchone()
except Exception as e:
print(e)
con.rollback()
return None
finally:
dbUtil.closeCon(con)
delete方法优化:加个判断
if reply == QMessageBox.StandardButton.Yes:
# 判断该图书类别下面是否有图书
if bookDao.countByTypeId(id)[0] > 0:
QMessageBox.warning(None, '系统提示', '该类别下有图书,不能删除!')
self.resetForm()
else:
if bookTypeDao.delete(id) > 0:
QMessageBox.information(None, '系统提示', '删除成功!')
self.initTable()
self.resetForm()
else:
QMessageBox.warning(None, '系统提示', '删除失败!')
运行测试: