pyqt5创建可以增删改查的数据库的界面的代码
时间: 2023-12-14 12:02:27 浏览: 108
非常感谢您的提问。以下是使用PyQt5创建可以增删改查的数据库界面的代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem, QVBoxLayout, QHBoxLayout, QWidget, QLabel, QLineEdit, QPushButton, QTableWidget, QMessageBox
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
class ContactsWindow(QMainWindow):
def __init__(self):
super().__init__()
# 设置窗口的标题和大小
self.setWindowTitle("联系人管理系统")
self.setMinimumSize(800, 600)
# 创建数据库连接
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName("contacts.db")
if not self.db.open():
QMessageBox.critical(None, "无法打开数据库", "无法连接数据库,添加联系人功能无法使用")
return
# 创建“联系人”表
query = QSqlQuery()
query.exec_(
"CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(40), phone VARCHAR(12), email VARCHAR(40))")
# 创建左侧的表格
self.table = QTableWidget(self)
self.table.setColumnCount(4)
self.table.setHorizontalHeaderLabels(["ID", "姓名", "手机", "邮箱"])
self.table.verticalHeader().setVisible(False)
self.load_contacts()
# 创建右侧的表单
self.name_label = QLabel("姓名:")
self.name_input = QLineEdit()
self.phone_label = QLabel("手机:")
self.phone_input = QLineEdit()
self.email_label = QLabel("邮箱:")
self.email_input = QLineEdit()
self.add_button = QPushButton("添加")
self.add_button.clicked.connect(self.add_contact)
self.update_button = QPushButton("更新")
self.update_button.clicked.connect(self.update_contact)
self.delete_button = QPushButton("删除")
self.delete_button.clicked.connect(self.delete_contact)
form_layout = QVBoxLayout()
form_layout.addWidget(self.name_label)
form_layout.addWidget(self.name_input)
form_layout.addWidget(self.phone_label)
form_layout.addWidget(self.phone_input)
form_layout.addWidget(self.email_label)
form_layout.addWidget(self.email_input)
form_layout.addWidget(self.add_button)
form_layout.addWidget(self.update_button)
form_layout.addWidget(self.delete_button)
form_widget = QWidget()
form_widget.setLayout(form_layout)
# 把左侧的表格和右侧的表单放到一个水平布局中
hbox = QHBoxLayout()
hbox.addWidget(self.table)
hbox.addWidget(form_widget)
# 把水平布局放到窗口中
central_widget = QWidget()
central_widget.setLayout(hbox)
self.setCentralWidget(central_widget)
# 从数据库中读取所有联系人信息,并显示在左侧的表格中
def load_contacts(self):
query = QSqlQuery()
query.exec_("SELECT * FROM contacts")
row = 0
while query.next():
self.table.insertRow(row)
self.table.setItem(row, 0, QTableWidgetItem(str(query.value(0))))
self.table.setItem(row, 1, QTableWidgetItem(str(query.value(1))))
self.table.setItem(row, 2, QTableWidgetItem(str(query.value(2))))
self.table.setItem(row, 3, QTableWidgetItem(str(query.value(3))))
row += 1
# 添加联系人
def add_contact(self):
name = self.name_input.text().strip()
phone = self.phone_input.text().strip()
email = self.email_input.text().strip()
if not name or not phone:
QMessageBox.warning(self, "警告", "姓名和手机不能为空")
return
query = QSqlQuery()
query.prepare("INSERT INTO contacts(name, phone, email) VALUES (:name, :phone, :email)")
query.bindValue(":name", name)
query.bindValue(":phone", phone)
query.bindValue(":email", email)
if query.exec_():
row = self.table.rowCount()
self.table.insertRow(row)
self.table.setItem(row, 0, QTableWidgetItem(str(query.lastInsertId())))
self.table.setItem(row, 1, QTableWidgetItem(name))
self.table.setItem(row, 2, QTableWidgetItem(phone))
self.table.setItem(row, 3, QTableWidgetItem(email))
self.name_input.setText("")
self.phone_input.setText("")
self.email_input.setText("")
else:
QMessageBox.critical(self, "添加联系人错误", "无法添加联系人")
# 更新联系人
def update_contact(self):
cur_row = self.table.currentRow()
if cur_row < 0:
QMessageBox.warning(self, "警告", "请先选择要更新的联系人")
return
id = int(self.table.item(cur_row, 0).text())
name = self.name_input.text().strip()
phone = self.phone_input.text().strip()
email = self.email_input.text().strip()
if not name or not phone:
QMessageBox.warning(self, "警告", "姓名和手机不能为空")
return
query = QSqlQuery()
query.prepare("UPDATE contacts SET name=:name, phone=:phone, email=:email WHERE id=:id")
query.bindValue(":name", name)
query.bindValue(":phone", phone)
query.bindValue(":email", email)
query.bindValue(":id", id)
if query.exec_():
self.table.setItem(cur_row, 1, QTableWidgetItem(name))
self.table.setItem(cur_row, 2, QTableWidgetItem(phone))
self.table.setItem(cur_row, 3, QTableWidgetItem(email))
self.name_input.setText("")
self.phone_input.setText("")
self.email_input.setText("")
else:
QMessageBox.critical(self, "更新联系人错误", "无法更新联系人")
# 删除联系人
def delete_contact(self):
cur_row = self.table.currentRow()
if cur_row < 0:
QMessageBox.warning(self, "警告", "请先选择要删除的联系人")
return
id = int(self.table.item(cur_row, 0).text())
query = QSqlQuery()
query.prepare("DELETE FROM contacts WHERE id=:id")
query.bindValue(":id", id)
if query.exec_():
self.table.removeRow(cur_row)
else:
QMessageBox.critical(self, "删除联系人错误", "无法删除联系人")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = ContactsWindow()
window.show()
sys.exit(app.exec_())
```
注意需要安装PyQt5和PyQt5-sqlite插件,以及SQLite数据库。
我希望这段代码能够解决您的问题。如果您有任何其他问题,请随时提出。
阅读全文