python mysql pyqt5 制作UI界面,通过按钮打开新的界面,并执行且显示mysql语句
```#主窗口
import pymysql
from functools import partial
import sys
from PyQt5.Qt import QWidget
from PyQt5 import QtGui,QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QFrame,QApplication,QDialog, QDialogButtonBox,QMessageBox,QVBoxLayout, QLineEdit,QTableWidgetItem,QTableWidget,QHBoxLayout)
#建立界面类
class creat_view(QDialog):
def __init__(self,parent = None):
super(creat_view,self).__init__(parent)
#设置界面大小、名称、背景
self.resize(1000,800)
self.setWindowTitle('贷款数据')
#窗体属性
self.setWindowFlags(Qt.Widget)
#连接数据库
db = pymysql.connect(
host='localhost',
user='root',
db='zbh',
port=3307,
charset='utf8'
)
#获取游标、数据
cur = db.cursor()
cur.execute("SELECT * FROM 副本数据模板")
data = cur.fetchall()
#数据列名
col_lst = [tup[0] for tup in cur.description]
#数据的大小
row = len(data)
vol = len(data[0])
#插入表格
self.MyTable = QTableWidget(row,vol)
font = QtGui.QFont('微软雅黑',10)
#设置字体、表头
self.MyTable.horizontalHeader().setFont(font)
self.MyTable.setHorizontalHeaderLabels(col_lst)
#设置竖直方向表头不可见
self.MyTable.verticalHeader().setVisible(False)
self.MyTable.setFrameShape(QFrame.NoFrame)
#设置表格颜色
self.MyTable.horizontalHeader().setStyleSheet('QHeaderView::section{background:skyblue}')
#构建表格插入数据
for i in range(row):
for j in range(vol):
temp_data = data[i][j] # 临时记录,不能直接插入表格
data1 = QTableWidgetItem(str(temp_data)) # 转换后可插入表格
self.MyTable.setItem(i, j, data1)
#编辑按钮
self.qle = QLineEdit()
buttonBox = QDialogButtonBox()
#增删查改四个按钮
addButton = buttonBox.addButton("&添加",QDialogButtonBox.ActionRole)
okButton = buttonBox.addButton("&保存",QDialogButtonBox.ActionRole)
deleteButton = buttonBox.addButton("&删除",QDialogButtonBox.ActionRole)
inquireButton = buttonBox.addButton("&查询",QDialogButtonBox.ActionRole)
openButton = buttonBox.addButton("&年龄比例",QDialogButtonBox.ActionRole)
#设置按钮内字体样式
addButton.setFont(font)
okButton.setFont(font)
deleteButton.setFont(font)
inquireButton.setFont(font)
openButton.setFont(font)
#垂直布局
layout = QVBoxLayout()
layout.addWidget(self.qle)
layout.addWidget(buttonBox)
layout.addWidget(self.MyTable)
self.setLayout(layout)
addButton.clicked.connect(partial(self.add_data,cur,db))#插入实现
okButton.clicked.connect(partial(self.save_data, cur, db,col_lst))#插入实现
deleteButton.clicked.connect(partial(self.del_data,cur,db))#删除实现
inquireButton.clicked.connect(partial(self.inq_data,cur,db))#查询实现
openButton.clicked.connect(partial(self.open_data,cur,db))#一类计算实现
#添加空表格
def add_data(self,cur,db):
#获取行数
row = self.MyTable.rowCount()
#在末尾插入一空行
self.MyTable.insertRow(row)
#插入数据
def save_data(self,cur,db,col_lst):
row_1 = self.MyTable.rowCount()
value_lst = []
for i in range(len(col_lst)):
if(len(self.MyTable.item(row_1-1,i).text())==0):
value_lst.append(None)
else:
value_lst.append(self.MyTable.item(row_1-1,i).text())
tup_va_lst = []
for cl,va in zip(col_lst,value_lst):
tup_va_lst.append((cl,va))
#插入语句
cur.execute('insert into 副本数据模板 (id,机构名称,客户号,证件号码,客户名称,联系电话,业务品种,合同号,借据号码,发放日,到期日,贷款金额,执行利率,担保方式,贷款形态,客户经理,贷款用途,客户地址,备注) values (%s,%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',value_lst)
db.commit()
#删除
def del_data(self,cur,db):
#是否删除的对话框
reply = QMessageBox.question(self, 'Message', 'Are you sure to delete it ?', QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.Yes:
#当前行
row_2 = self.MyTable.currentRow()
del_d = self.MyTable.item(row_2, 0).text()
#在数据库删除数据
cur.execute("DELETE FROM 副本数据模板 WHERE id = '"+del_d+"'")
db.commit()
#删除表格
self.MyTable.removeRow(row_2)
#查询
def inq_data(self,cur,db):
txt = self.qle.text()
#模糊查询
if len(txt) != 0:
cur.execute("SELECT * FROM 副本数据模板 where 机构名称 like '%"+txt+"%' or 客户号 like '%"+txt+"%' or 证件号码 like '%"+txt+"%'or 客户名称 like '%"+txt+"%' or 合同号 like '%"+txt+"%' or 借据号码 like '%"+txt+"%' or 贷款形态 like '%"+txt+"%'")
data_x = cur.fetchall()
self.MyTable.clearContents()
row_4 = len(data_x)
vol_1 = len(cur.description)
#查询到的更新带表格当中
for i_x in range(row_4):
for j_y in range(vol_1):
temp_data_1 = data_x[i_x][j_y] # 临时记录,不能直接插入表格
data_1 = QTableWidgetItem(str(temp_data_1)) # 转换后可插入表格
self.MyTable.setItem(i_x, j_y, data_1)
#空输入返回原先数据表格
else:
self.MyTable.clearContents()
cur.execute("SELECT * FROM 副本数据模板")
data_y = cur.fetchall()
row_5 = len(data_y)
vol_1 = len(cur.description)
for i_x_1 in range(row_5):
for j_y_1 in range(vol_1):
temp_data_2 = data_y[i_x_1][j_y_1] # 临时记录,不能直接插入表格
data_2 = QTableWidgetItem(str(temp_data_2)) # 转换后可插入表格
self.MyTable.setItem(i_x_1, j_y_1, data_2)
#打开副窗口
def open_data(self,cur,db):
#模糊查询
if len(txt) != 0:
cur.execute("SELECT 贷款形态, 25岁以下/(select SUM(25岁以下) from 计算1 b)*100 as 25岁以下,`26~35岁`/(select SUM(`26~35岁`) from 计算1 b)*100 as `26~35岁`,`36~45岁`/(select SUM(`36~45岁`) from 计算1 b)*100 as `36~45岁`,`46~55岁`/(select SUM(`46~55岁`) from 计算1 b)*100 as `46~55岁`,`56~65岁`/(select SUM(`56~65岁`) from 计算1 b)*100 as `56~65岁`,`66~75岁`/(select SUM(`66~75岁`) from 计算1 b)*100 as `66~75岁`,`75岁以上`/(select SUM(`75岁以上`) from 计算1 b)*100 as 75岁以上 FROM 计算1 a GROUP BY 贷款形态")
data_x = cur.fetchall()
self.MyTable.clearContents()
row_4 = len(data_x)
vol_1 = len(cur.description)
#查询到的更新带表格当中
for i_x in range(row_4):
for j_y in range(vol_1):
temp_data_1 = data_x[i_x][j_y] # 临时记录,不能直接插入表格
data_1 = QTableWidgetItem(str(temp_data_1)) # 转换后可插入表格
self.MyTable.setItem(i_x, j_y, data_1)
#空输入返回原先数据表格
else:
self.MyTable.clearContents()
cur.execute("SELECT * FROM 计算1")
data_y = cur.fetchall()
row_5 = len(data_y)
vol_1 = len(cur.description)
for i_x_1 in range(row_5):
for j_y_1 in range(vol_1):
temp_data_2 = data_y[i_x_1][j_y_1] # 临时记录,不能直接插入表格
data_2 = QTableWidgetItem(str(temp_data_2)) # 转换后可插入表格
self.MyTable.setItem(i_x_1, j_y_1, data_2)
def main():
#显示
app = QApplication(sys.argv)
c = creat_view()
c.show()
sys.exit(app.exec_())
main()
#副窗口
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets,QtGui,QtCore
import pymysql
class Demo(object):
def __init__(self,parent=None):
super(Demo,self).__init__(parent)
self.initUI() # 初始化窗口
def initUI(self):
self.setWindowTitle("使用表格显示数据库中的数据")
self.resize(400,180) # 设置窗口大小
vhayout=QHBoxLayout() # 创建水平布局
table=QTableWidget() # 创建表格
font = QtGui.QFont('微软雅黑', 10)
db = pymysql.connect(host='localhost',
user='root',
db='zbh',
port=3307,
charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
cursor.execute("select * from test1")
col_lst = [tup[0] for tup in cursor.description]
# 设置字体、表头
table.horizontalHeader().setFont(font)
table.setHorizontalHeaderLabels(col_lst)
# 设置竖直方向表头不可见
table.verticalHeader().setVisible(False)
table.setFrameShape(QFrame.NoFrame)
# 设置表格颜色
table.horizontalHeader().setStyleSheet('QHeaderView::section{background:skyblue}')
# 打开数据库连接
result=cursor.fetchall() # 获取所有记录
row = cursor.rowcount # 取得记录个数,用于设置表格的行数
vol = len(result[0]) # 取得字段数,用于设置表格的列数
cursor.close() # 关闭游标
db.close() # 关闭连接
table.setRowCount(row) # 设置表格行数
table.setColumnCount(vol) # 设置表格列数
for i in range(row): # 遍历行
for j in range(vol): # 遍历列
data = QTableWidgetItem(str(result[i][j])) # 转换后可插入表格
table.setItem(i, j, data)
table.resizeColumnsToContents() # 使列宽跟随内容改变
table.resizeRowsToContents() # 使行高度跟随内容改变
table.setAlternatingRowColors(True) # 使表格颜色交错显示
vhayout.addWidget(table) # 将表格添加到水平布局中
self.setLayout(vhayout) # 设置当前窗口的布局方式
if __name__=='__main__':
import sys
app=QApplication(sys.argv) # 创建窗口程序
demo=Demo() # 创建窗口类对象
demo.show() # 显示窗口
sys.exit(app.exec_())
两段程序都可以单独运行,但主窗口中 open按钮怎么定义都打不开副窗口
QDialog和QWidget都试过,MainWindow不熟不敢乱改
程序通过open按钮打开副窗口并显示,同时主窗口不关闭