PyQt5-数据库查询
PyQt5-数据库查询
博主在写数据库课程的大作业,想用pyqt5设计一个可视化界面方便对数据库的操作。为了简便学习,先只对数据库的一张表进行增操作
UI展示
- 通过QTDesigner进行界面设计
代码展示
import pymysql
import sys
from single_insert import Ui_MainWindow
from PyQt5.QtWidgets import QApplication,QMainWindow,QMessageBox
# 写一个子类简便对主窗口的操作
class Run_MainWindow(Ui_MainWindow, QMainWindow):
def __init__(self):
super(Run_MainWindow, self).__init__()
self.setupUi(self)
self.lineEdit=self.lineEdit
self.label_3=self.label_3
self.label_2=self.label_2
self.lineEdit_2 = self.lineEdit_2
self.label = self.label
self.lineEdit_3 = self.lineEdit_3
self.pushButton.clicked.connect(self.insertTBuarea)
self.pushButton_2=self.pushButton_2
# 数据库——增一条数据功能
def insertTBuarea(self):
print("面积:{0},功能:{1}".format(self.lineEdit_2.text(),self.lineEdit_3.text()))
global a, b
a=self.lineEdit_2.text()
b=self.lineEdit_3.text()
# a,b格式错误则弹出对话框,先省略
# 打开数据库连接
db = pymysql.connect(此处省略)
sql = "INSERT INTO uarea(asqure,afuncation) VALUES ('{0}','{1}')".format(a, b)
print(sql)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
# 提交成功显示一个对话框
self.show_messages()
except:
# 如果发生错误则回滚
print("数据提交失败!")
db.rollback()
# 关闭数据库连接
db.close()
def show_messages(self):
QMessageBox.information(self,"增添数据","任务完成",QMessageBox.Yes)
if __name__ == '__main__':
app = QApplication(sys.argv)
MainWindow = Run_MainWindow()
MainWindow.show()
sys.exit(app.exec())
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)