和原来的代码写到一起,给我一个能运行的完整代码
时间: 2024-11-20 20:35:45 浏览: 3
js代码-在线运行学习es6(react)
为了保持代码的完整性,以下是将异常处理合并到原有代码中的版本。请注意,我已经把异常处理添加到了`db_connect`和`sql_exec`方法中:
```python
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QTableView
from ui.DBDialog import *
from PyQt5.QtGui import QMessageBox
class DBDemo(Ui_Dialog, QTableView):
def __init__(self):
super(DBDemo, self).__init__()
self.setupUi(self)
self.btnCancel.clicked.connect(self.close)
self.db = None
self.db_connect()
self.sql_exec()
def db_connect(self):
try:
self.db = QSqlDatabase.addDatabase('QSQLITE')
self.db.setDatabaseName('./example.db')
if not self.db.open():
QMessageBox.critical(self, 'Database Connection', self.db.lastError().text())
except QSqlError as e:
QMessageBox.critical(self, 'Database Error', str(e))
def closeEvent(self, QCloseEvent):
if self.db is not None:
self.db.close()
def sql_exec(self):
try:
self.model = QSqlTableModel(self)
self.model.setTable('users')
self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
self.model.setHeaderData(0, Qt.Horizontal, 'id')
self.model.setHeaderData(1, Qt.Horizontal, 'name')
self.model.setHeaderData(2, Qt.Horizontal, 'age')
self.model.select()
self.tableView.setModel(self.model)
self.tableView.setSelectionBehavior(QTableView.SelectRows)
self.btnDelete.clicked.connect(self.deleteRow)
except QSqlError as e:
QMessageBox.warning(self, 'SQL Execution Error', str(e))
def deleteRow(self):
index = self.tableView.currentIndex()
if index.isValid():
row = index.row()
id = self.model.record(row).value('id')
name = self.model.record(row).value('name')
age = self.model.record(row).value('age')
msg = f"是否删除选定的【{id}-{name}-{age}】"
reply = QMessageBox.question(self, "删除", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
self.model.removeRow(row)
self.model.submitAll()
self.model.select()
self.tableView.setModel(self.model)
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = DBDemo()
demo.show()
```
现在,如果你的环境配置正确并且example.db文件存在,这段代码应该能正确地建立数据库连接,执行SQL查询,并处理可能出现的错误,避免程序因异常而终止。
阅读全文