PyQt5-数据库查询

PyQt5-数据库查询

博主在写数据库课程的大作业,想用pyqt5设计一个可视化界面方便对数据库的操作。为了简便学习,先只对数据库的一张表进行增操作

UI展示

  • 通过QTDesigner进行界面设计
    123

代码展示

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())
posted @ 2022-05-01 20:33  梧桐灯下江楚滢  阅读(351)  评论(0编辑  收藏  举报