python 操作数据库mysql workbench 8.0 以及 QT5的简例

附件UI的python
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(389, 240)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(0, 0, 91, 31))
        self.pushButton.setStyleSheet("color: rgb(235, 0, 205);\n"
"background-color: rgb(255, 239, 241);")
        self.pushButton.setObjectName("pushButton")
        self.textEdit = QtWidgets.QTextEdit(Form)
        self.textEdit.setGeometry(QtCore.QRect(0, 40, 381, 191))
        self.textEdit.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
        self.textEdit.setStyleSheet("background-color: rgb(255, 220, 233);")
        self.textEdit.setFrameShape(QtWidgets.QFrame.Box)
        self.textEdit.setObjectName("textEdit")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(100, 0, 81, 31))
        self.pushButton_2.setStyleSheet("background-color: rgb(164, 169, 255);")
        self.pushButton_2.setObjectName("pushButton_2")

        self.retranslateUi(Form)
        self.pushButton.clicked.connect(Form.hello)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "why"))
        self.pushButton_2.setText(_translate("Form", "test"))

  



import sys
# from PyQt5.QtWidgets import QApplication,QMainWindow
# from PyQt5 import QtWidgets
from PyQt5 import QtWidgets
from untitled import Ui_Form
import mysql.connector
class MyButton(QtWidgets.QMainWindow, Ui_Form):
def __init__(self):
super(MyButton, self).__init__()
self.setupUi(self)


config = {
'host': '192.168.6.28',
'user': 'root',
'password': '1234',
'port': 3306,
'database': 'test', #数据库名称
'charset': 'utf8'
}
self.mysql = None
self.cursor = None
try:
self.mysql = mysql.connector.connect(**config)
self.cursor = self.mysql.cursor()
except mysql.connector.Error as e:
# print('connect fails!{}'.format(e))
# strx = "aaa{}".format("sssss")
self.textEdit.setText(str('connect fails!\n{}'.format(e)))

def get_sqldata(self, sql_query):
try:
# sql_query = 'select * from new_table;'
self.cursor.execute(sql_query)
lx = self.cursor.fetchall()
return lx
except mysql.connector.Error as e:
self.textEdit.setText(str('connect fails!\n{}'.format(e)))

def close_sql(self):
self.mysql.close()

  #映射的按钮事件
def hello(self):
sql_query = 'select * from new_table;'
lx = self.get_sqldata(sql_query)
self.pushButton.setText("hello")
self.textEdit.setText("this is hello" + str(lx))


if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv) # app
window = MyButton()
window.show() # 显示
sys.exit(app.exec_())


posted @ 2021-07-28 15:16  默*为  阅读(301)  评论(0编辑  收藏  举报