PyQt5+MySQL+PyMySQL模块实现个简单的增删改查,代码示例
时间: 2023-09-25 08:06:34 浏览: 388
PyQt5 + MySQL简单示例
### 回答1:
以下是一个简单的 PyQt5 MySQL PyMySQL 模块实现增删改查的示例代码:
```python
import pymysql
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, QMessageBox, QTableWidget, QTableWidgetItem
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('PyQt5 MySQL PyMySQL')
self.setGeometry(300, 300, 500, 500)
# 连接 MySQL 数据库
self.conn = pymysql.connect(host='localhost', user='root', password='password', database='test', charset='utf8')
self.cursor = self.conn.cursor()
# 创建控件
self.label1 = QLabel('姓名')
self.label2 = QLabel('年龄')
self.label3 = QLabel('性别')
self.nameEdit = QLineEdit()
self.ageEdit = QLineEdit()
self.genderEdit = QLineEdit()
self.addButton = QPushButton('添加')
self.deleteButton = QPushButton('删除')
self.updateButton = QPushButton('更新')
self.queryButton = QPushButton('查询')
self.tableWidget = QTableWidget()
# 布局
hbox1 = QHBoxLayout()
hbox1.addWidget(self.label1)
hbox1.addWidget(self.nameEdit)
hbox1.addWidget(self.label2)
hbox1.addWidget(self.ageEdit)
hbox1.addWidget(self.label3)
hbox1.addWidget(self.genderEdit)
hbox2 = QHBoxLayout()
hbox2.addWidget(self.addButton)
hbox2.addWidget(self.deleteButton)
hbox2.addWidget(self.updateButton)
hbox2.addWidget(self.queryButton)
vbox = QVBoxLayout()
vbox.addLayout(hbox1)
vbox.addLayout(hbox2)
vbox.addWidget(self.tableWidget)
self.setLayout(vbox)
# 信号槽连接
self.addButton.clicked.connect(self.addRecord)
self.deleteButton.clicked.connect(self.deleteRecord)
self.updateButton.clicked.connect(self.updateRecord)
self.queryButton.clicked.connect(self.queryRecord)
# 显示窗口
self.show()
def addRecord(self):
name = self.nameEdit.text()
age = self.ageEdit.text()
gender = self.genderEdit.text()
if name and age and gender:
sql = "INSERT INTO students (name, age, gender) VALUES ('{}', {}, '{}')".format(name, age, gender)
try:
self.cursor.execute(sql)
self.conn.commit()
QMessageBox.information(self, '添加成功', '添加记录成功!')
except Exception as e:
self.conn.rollback()
QMessageBox.warning(self, '添加失败', '添加记录失败:{}'.format(str(e)))
else:
QMessageBox.warning(self, '添加失败', '请填写完整信息!')
def deleteRecord(self):
row = self.tableWidget.currentRow()
if row >= :
id = self.tableWidget.item(row, ).text()
sql = "DELETE FROM students WHERE id = {}".format(id)
try:
self.cursor.execute(sql)
self.conn.commit()
self.tableWidget.removeRow(row)
QMessageBox.information(self, '删除成功', '删除记录成功!')
except Exception as e:
self.conn.rollback()
QMessageBox.warning(self, '删除失败', '删除记录失败:{}'.format(str(e)))
else:
QMessageBox.warning(self, '删除失败', '请选择要删除的记录!')
def updateRecord(self):
row = self.tableWidget.currentRow()
if row >= :
id = self.tableWidget.item(row, ).text()
name = self.nameEdit.text()
age = self.ageEdit.text()
gender = self.genderEdit.text()
if name and age and gender:
sql = "UPDATE students SET name = '{}', age = {}, gender = '{}' WHERE id = {}".format(name, age, gender, id)
try:
self.cursor.execute(sql)
self.conn.commit()
self.tableWidget.setItem(row, 1, QTableWidgetItem(name))
self.tableWidget.setItem(row, 2, QTableWidgetItem(age))
self.tableWidget.setItem(row, 3, QTableWidgetItem(gender))
QMessageBox.information(self, '更新成功', '更新记录成功!')
except Exception as e:
self.conn.rollback()
QMessageBox.warning(self, '更新失败', '更新记录失败:{}'.format(str(e)))
else:
QMessageBox.warning(self, '更新失败', '请填写完整信息!')
else:
QMessageBox.warning(self, '更新失败', '请选择要更新的记录!')
def queryRecord(self):
self.tableWidget.clear()
self.tableWidget.setColumnCount(4)
self.tableWidget.setHorizontalHeaderLabels(['ID', '姓名', '年龄', '性别'])
sql = "SELECT * FROM students"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
self.tableWidget.setRowCount(len(results))
for i, row in enumerate(results):
for j, col in enumerate(row):
self.tableWidget.setItem(i, j, QTableWidgetItem(str(col)))
except Exception as e:
QMessageBox.warning(self, '查询失败', '查询记录失败:{}'.format(str(e)))
def closeEvent(self, event):
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
app = QApplication([])
ex = Example()
app.exec_()
```
注意:这只是一个简单的示例代码,实际应用中需要根据具体情况进行修改和优化。
### 回答2:
使用PyQt5和PyMySQL模块实现一个简单的增删改查操作,以下是代码示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox, QTableWidgetItem, QTableWidget
import pymysql
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.db = pymysql.connect("localhost", "username", "password", "database_name")
self.cursor = self.db.cursor()
def initUI(self):
self.setWindowTitle("简单的增删改查")
self.setGeometry(300, 300, 500, 350)
self.centralWidget = QWidget(self)
self.setCentralWidget(self.centralWidget)
self.layout = QVBoxLayout()
self.centralWidget.setLayout(self.layout)
self.inputLayout = QHBoxLayout()
self.layout.addLayout(self.inputLayout)
self.nameLabel = QLabel("姓名:")
self.inputLayout.addWidget(self.nameLabel)
self.nameInput = QLineEdit()
self.inputLayout.addWidget(self.nameInput)
self.addButton = QPushButton("添加")
self.addButton.clicked.connect(self.addRecord)
self.layout.addWidget(self.addButton)
self.tableWidget = QTableWidget()
self.layout.addWidget(self.tableWidget)
self.loadTable()
def loadTable(self):
self.cursor.execute("SELECT * FROM students")
results = self.cursor.fetchall()
self.tableWidget.setRowCount(len(results))
self.tableWidget.setColumnCount(2)
self.tableWidget.setHorizontalHeaderLabels(["ID", "姓名"])
for i, row in enumerate(results):
for j, value in enumerate(row):
self.tableWidget.setItem(i, j, QTableWidgetItem(str(value)))
def addRecord(self):
name = self.nameInput.text()
if name:
sql = "INSERT INTO students (name) VALUES ('%s')" % name
try:
self.cursor.execute(sql)
self.db.commit()
self.nameInput.clear()
self.loadTable()
except:
self.db.rollback()
QMessageBox.warning(self, "Error", "添加记录失败")
else:
QMessageBox.warning(self, "Error", "姓名不能为空")
def closeEvent(self, event):
self.cursor.close()
self.db.close()
if __name__ == "__main__":
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
```
上述代码实现了一个简单的GUI界面,包含一个用于输入姓名的文本框和一个用于添加记录的按钮。数据存储在MySQL数据库的`students`表中,其中包含`id`和`name`两个字段。点击添加按钮后将会将姓名插入到数据库中,并更新显示在表格中。表格使用QTableWidget来显示。通过`PyMySQL`模块连接和操作数据库。
### 回答3:
以下是使用PyQt5和PyMySQL模块实现简单的增删改查的代码示例:
```python
import pymysql
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QPushButton, QVBoxLayout, QWidget
class DatabaseWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("数据库操作")
self.setGeometry(100, 100, 400, 300)
self.table_widget = QTableWidget()
self.setCentralWidget(self.table_widget)
self.btn_refresh = QPushButton("刷新")
self.btn_refresh.clicked.connect(self.refresh_data)
self.btn_add = QPushButton("添加")
self.btn_add.clicked.connect(self.add_data)
self.btn_delete = QPushButton("删除")
self.btn_delete.clicked.connect(self.delete_data)
self.btn_update = QPushButton("更新")
self.btn_update.clicked.connect(self.update_data)
layout = QVBoxLayout()
layout.addWidget(self.btn_refresh)
layout.addWidget(self.btn_add)
layout.addWidget(self.btn_delete)
layout.addWidget(self.btn_update)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
self.db = pymysql.connect(host='localhost', user='root', password='password', db='testdb')
self.cursor = self.db.cursor()
self.refresh_data()
def refresh_data(self):
self.table_widget.clear()
self.cursor.execute("SELECT * FROM users")
data = self.cursor.fetchall()
self.table_widget.setRowCount(len(data))
self.table_widget.setColumnCount(len(data[0]))
for i, row in enumerate(data):
for j, value in enumerate(row):
item = QTableWidgetItem(str(value))
self.table_widget.setItem(i, j, item)
def add_data(self):
self.cursor.execute("INSERT INTO users (name, age) VALUES ('John', 30)")
self.db.commit()
self.refresh_data()
def delete_data(self):
selected_row = self.table_widget.currentRow()
id = self.table_widget.item(selected_row, 0).text()
self.cursor.execute(f"DELETE FROM users WHERE id={id}")
self.db.commit()
self.refresh_data()
def update_data(self):
selected_row = self.table_widget.currentRow()
id = self.table_widget.item(selected_row, 0).text()
self.cursor.execute(f"UPDATE users SET name='Mike', age=25 WHERE id={id}")
self.db.commit()
self.refresh_data()
if __name__ == '__main__':
app = QApplication([])
window = DatabaseWindow()
window.show()
app.exec_()
```
此示例展示了一个使用PyQt5和PyMySQL模块实现的简单的数据库操作窗口。窗口中包含一个表格用于显示数据库中的数据。通过点击不同按钮,可以刷新数据,添加数据,删除数据和更新数据。代码中的数据库连接参数需要根据实际情况进行修改。
阅读全文