赞
踩
在这里我们基于Python-Windows+Pycharm+PyQt5基础环境配置,1000%解决你的环境问题(一)的学习,我们搭建好PyQt5的基础环境,这里我们将进行制作一个简单的软件-----数据写入展示;
基础环境:
在这里我们需要安装MySQL的包
pip install pymysql -i https://pypi.doubanio.com/simple #加入豆瓣源
1、连接数据库,获取游标
""" 配置端口、用户名、主机、密码 """ def get_conn(): try: conn = mysql_conn.Connection(host='127.0.0.1',#主机 user='root',#用户 port=3306,#端口 password='123456',#密码 charset='utf8',#编码 db='library'#数据库 ) return conn except mysql_conn.Error: print('连接错误')
2、关闭连接
def close_conn(conn,cursor): try: if cursor: cursor.close() if conn: conn.close() except Exception as s: print(s) finally: try: cursor.close() except: pass try: conn.close() except: pass
在QT界面设计我们需要三个组件
# 数据库处理---数据库操作 添加 #1、添加类别 def add_Tab2_LeiBie(self): #数据库操作流程 #1、获取连接 conn = get_conn() #2、获取cursor cur = conn.cursor() #3、sql语句 sql = 'insert into 类别(leibie_name) values(%s)'#这里的类别是表,leibie_name是列名 leibie_name = self.Tab2_LeiBie.text()#获取类别文本框信息 #4、执行语句 cur.execute(sql,(leibie_name)) #5、insert,update,delete必须提交显示 conn.commit() #6、关闭资源 close_conn(conn,cur) #7、消息消息提示 # 方法一、 #self.statusBar().showMessage('添加成功') # 方法二、 self.tishikuang() # 删除lineEdit内的内容 self.Tab2_LeiBie.setClearButtonEnabled(True)#提示删除文本框内的内容 self.show_Tab2_LeiBie()
# 显示已有类别,并且添加网直接看见 查询 def show_Tab2_LeiBie(self): conn = get_conn() cur = conn.cursor() sql = 'select leibie_name from 类别' cur.execute(sql) data = cur.fetchall() if data: """ 要获取当前表格部件中的行数,可以通过rowCount()方法获取, 要设置表格部件的行数,可以通过setRowCount(int rows)调整表格的行数, 如果参数rows小于现在表格中的实际行数,则表格中超出参数的行数数据会丢弃, 就算是后面将行数或列数恢复也不能恢复相关数据 """ self.Tab2_LeiBieBiao.setRowCount(0)#获取行数 self.Tab2_LeiBieBiao.insertRow(0)#插入o行 for row,form in enumerate(data): for column,item in enumerate(form): self.Tab2_LeiBieBiao.setItem(row,column,QTableWidgetItem(str(item)))#行,列,赋值 column += 1 row_postition = self.Tab2_LeiBieBiao.rowCount() self.Tab2_LeiBieBiao.insertRow(row_postition)
希望这篇博文对你有用!
谢谢点赞评论!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。