用pythonQT生成一个界面 可以将mysql里面的数据增删改查表中字段包含姓名和案件名称
以下是一个简单的示例代码:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem
import mysql.connector
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 连接数据库
self.cnx = mysql.connector.connect(user='root', password='password', host='localhost', database='testdb')
self.cursor = self.cnx.cursor()
# 姓名和案件名称输入框
self.name_edit = QLineEdit()
self.case_edit = QLineEdit()
# 添加按钮
add_button = QPushButton('添加')
add_button.clicked.connect(self.add_data)
# 删除按钮
del_button = QPushButton('删除')
del_button.clicked.connect(self.del_data)
# 修改按钮
update_button = QPushButton('修改')
update_button.clicked.connect(self.update_data)
# 工具栏水平布局
toolbar_layout = QHBoxLayout()
toolbar_layout.addWidget(QLabel('姓名:'))
toolbar_layout.addWidget(self.name_edit)
toolbar_layout.addWidget(QLabel('案件名称:'))
toolbar_layout.addWidget(self.case_edit)
toolbar_layout.addWidget(add_button)
toolbar_layout.addWidget(del_button)
toolbar_layout.addWidget(update_button)
# 表格
self.table = QTableWidget()
self.table.setColumnCount(2)
self.table.setHorizontalHeaderLabels(['姓名', '案件名称'])
self.update_table()
# 垂直布局
layout = QVBoxLayout()
layout.addLayout(toolbar_layout)
layout.addWidget(self.table)
self.setLayout(layout)
self.show()
def update_table(self):
# 查询数据
self.cursor.execute('SELECT * FROM data')
data = self.cursor.fetchall()
# 清空表格
self.table.setRowCount(0)
# 填充表格
for row in data:
self.table.insertRow(0)
self.table.setItem(0, 0, QTableWidgetItem(row[0]))
self.table.setItem(0, 1, QTableWidgetItem(row[1]))
def add_data(self):
# 获取输入框的值
name = self.name_edit.text()
case = self.case_edit.text()
# 插入数据
self.cursor.execute('INSERT INTO data (name, case_name) VALUES (%s, %s)', (name, case))
self.cnx.commit()
# 更新表格
self.update_table()
def del_data(self):
# 获取选择的行
selected = self.table.selectedItems()
if len(selected) == 0:
return
# 获取要删除的行号和姓名
row = selected[0].row()
name = self.table.item(row, 0).text()
# 删除数据
self.cursor.execute('DELETE FROM data WHERE name = %s', (name,))
self.cnx.commit()
# 更新表格
self.update_table()
def update_data(self):
# 获取选择的行
selected = self.table.selectedItems()
if len(selected) == 0:
return
# 获取要修改的行号和姓名
row = selected[0].row()
name = self.table.item(row, 0).text()
# 获取新的值
new_name = self.name_edit.text()
new_case = self.case_edit.text()
# 更新数据
self.cursor.execute('UPDATE data SET name = %s, case_name = %s WHERE name = %s', (new_name, new_case, name))
self.cnx.commit()
# 更新表格
self.update_table()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
注意,这个示例代码使用了mysql.connector模块连接数据库,因此需要先安装该模块。可以使用以下命令安装:
pip install mysql-connector-python
另外,示例代码中的数据库名为testdb,表名为data,包含两个字段name和case_name,如果需要使用该代码,需要先创建这个数据库和表
原文地址: https://www.cveoy.top/t/topic/fquc 著作权归作者所有。请勿转载和采集!