pyside2入门–药品管理ui 1.0 补充:1、树状任务导入导出。2、后端入门处理
下次改进:写一个小弹窗,让用户输入要存储导入的任务名。
一、实验环境与心得体会
环境不变
from PySide2.QtWidgets import QApplication, QMessageBox,QTreeWidgetItem
from PySide2.QtUiTools import QUiLoader
import MySQLdb
谈谈心得体会:确实一开始感觉实现应该不太难,但是实际过程中遇到了很多问题。这和单纯的写算法有很大区别,得按照别人的框架,写好的类,修改算法,会遇到各种情况,但是不用怕,你遇到的问题网上都有人遇到过,所以,坚持就好。
1、一开始建数据库表,没写主键,IDname,IDstr会自动排序,根本不是实际情况。所以还是要写上主键。然后,写上主键了,输出也不按广搜顺序来,这里是大概情况,两个解决方法,order by主键,或者导出的数据先排序。
2、批量导入得时候,s%又不用加‘’了,我也挺迷得。然后int型,也最好用%s导入,不然遇到了一个int not callalbe得bug。
3、广搜出点,广搜加点。用一个IDstr,存的是任务之间还有多少个任务。
4、遇到bug不用怕,坚持。
二、实验结果。
1、初始数据库
2、树任务的注册
3、查看数据库结果,比对广搜树。可以看出IDstr的效果。
4、重新导入数据库。
bingo!
三、代码分析。
1、导出代码。
def shuchu(self):
data=[]#存数据库,str,IDname
a = []#存实体treeItem类,便于广搜
lenth = self.ui.treeWidget.topLevelItemCount()#开始根节点几个
for i in range(lenth):
a.append(self.ui.treeWidget.topLevelItem(i))#存根节点
data.append(self.ui.treeWidget.topLevelItem(i).text(0))#存根节点内容
lu = [lenth]#存任务之间有多少个任务
head = 0#头,尾,广度
tail = lenth#前面已经存好了
while head < tail:#广搜
i=0#i的作用,重新开始添加
while a[head].child(i) != None: # 所有子节点遍历添加
a.append(a[head].child(i))
data.append(a[head].child(i).text(0))
i+=1
tail += 1
lu.append(tail)#任务之间有多少个
head+=1
lu.pop(-1)#最后一个没必要
# print(a)
# print(lu)
# print(data)
data1=[]#存数据库
for i in range(len(lu)):
data1.append((i,data[i],lu[i]))
db = MySQLdb.connect("localhost", "root", "。。。", "test", charset='utf8')
cursor = db.cursor()
sql = "INSERT INTO one(ID,IDname,IDstr) VALUES (%s,%s,%s )"#很玄学,现在又不用‘’了,以前要。。
try:
cursor.executemany(sql, data1)#批量存
db.commit()
QMessageBox.about(self.ui, '正常', '树任务注册成功')
except Exception as e:
db.rollback() # Rollback in case there is any error
print('错误:', e)
QMessageBox.critical(self.ui, '错误', f'错误类型:{e}')
db.close() # 关闭数据库连接
2、导入代码
def shuru(self):
db = MySQLdb.connect("localhost", "root", "。。。", "test", charset='utf8')
cursor = db.cursor()
sql = "SELECT * FROM one order by ID"###关键要排序!!!必须的主键,IDstr不行。
try:
cursor.execute(sql)
data = cursor.fetchall()
except Exception as e:
print('错误:', e)
db.close()
# print(data[0][1],type(data[0][1]))#0.0.0.0.0.1:1 <class 'str'>
# print(data[0][2], type(data[0][2]))#2 <class 'str'>
data1=[]
lu=[]
#data=list(data)
#data.sort()
#print(data)
try:
lenend=int(data[-1][2])#总共节点
lentop=int(data[0][2])#起始根数目
for i in range(lenend):
data1.append(data[i][1])
lu.append(int(data[i][2]))
# print(data1,lu)
# print(lenend,lentop)
a=[]#实例树类,用它加文本
self.ui.treeWidget.clear() # 清空
for i in range(lentop):
root = QTreeWidgetItem(self.ui.treeWidget)
root.setText(0, f'{data1[i]}')
a.append(root) # 存根节点
head = 0#
tail = lentop
while head < tail:# 所有子节点遍历添加
for i in range(lu[head],lu[head+1]):
child = QTreeWidgetItem(a[head])
child.setText(0, f'{data1[tail]}')
a.append(child)
tail += 1
if tail==lenend:
break#已经添加完了
head+=1
QMessageBox.about(self.ui, '正常', '树任务导出成功')
except Exception as e:
QMessageBox.critical(self.ui, '错误', f'错误类型:{e}')