python遍歷資料庫畫樹狀圖
阿新 • • 發佈:2022-04-07
sql中有中文條件查詢死活不出來
把中文給變數然後%s傳參也不行,只能傳編碼多巢狀一層去查中文名稱
暫時沒有找到解決方法
這個庫貌似也沒辦法寫入中文名
from PIL import Image, ImageDraw import pymssql class RelationTree: def __init__(self, basewidth=100, basedepth=100): self.basewidth = basewidth self.basedepth = basedepth self.root = None def gentree(self, db, mothervalue, tablename, childcol, mothercol): self.root = decisionnode(mothervalue) cur = db.cursor() def swap_gentree(node): cur.execute("select %s from %s where %s = '%s' and SSMK = 4 " % \ (childcol, tablename, mothercol, node.value)) results = cur.fetchall() print("資料庫查詢完成") # 如果是葉子節點,則直接返回 if not results: return decisionnode(node.value, isleaf=True, maxlevel=1) # return decisionnode(results[1], isleaf=True, maxlevel=1) # 程式執行到這裡,說明是非葉子節點 # 對非葉子節點進行其下包含的葉子節點進行統計(leafcounts) # 該節點之下最深的深度maxlevel收集 maxlevel = 1 for each in results: print(each) entrynode = swap_gentree(decisionnode(each[0])) if (entrynode.isleaf): #如果是葉子節點 node.leafcounts += 1 else:#如果不是葉子節點 node.leafcounts += entrynode.leafcounts #擴充套件深度 if (entrynode.maxlevel > maxlevel): maxlevel = entrynode.maxlevel node.addchild(entrynode) node.maxlevel = maxlevel + 1 return node swap_gentree(self.root) def draweachnode(self, tree, draw, x, y): draw.text((x, y), tree.value, (0, 0, 0)) if not tree.childs: return childs_leafcounts = [child.leafcounts if child.leafcounts else 1 for child in tree.childs] leafpoint = x - sum(childs_leafcounts) * self.basewidth / 2 cumpoint = 0 for childtree, point in zip(tree.childs, childs_leafcounts): centerpoint = leafpoint + self.basewidth * cumpoint + self.basewidth * point / 2 cumpoint += point draw.line((x, y, centerpoint, y + self.basedepth), (255, 0, 0)) self.draweachnode(childtree, draw, centerpoint, y + self.basedepth) def drawTree(self, filename='tree.png'): width = self.root.leafcounts * self.basewidth + self.basewidth depth = self.root.maxlevel * self.basedepth + self.basedepth img = Image.new(mode="RGB", size=(width, depth), color=(255, 255, 255)) draw = ImageDraw.Draw(img) self.draweachnode(self.root, draw, width / 2, 20) img.save(filename) class decisionnode: def __init__(self, value, isleaf=False, leafcounts=0, maxlevel=1): self.childs = [] self.value = value self.isleaf = isleaf self.leafcounts = leafcounts self.maxlevel = maxlevel def addchild(self, child): self.childs.append(child) if __name__ == '__main__': # gentree 方法用於生成整棵樹,需要傳值:db:資料庫連線,mathervalue:根節點的數值 tablename:資料庫表名 childcol:子節點在表中的對應的欄位名稱 mothercol:上級節點在表中的欄位名稱 # gentree(self, db, mothervalue, tablename, childcol, mothercol): # 資料庫連線:根節點的數值:資料庫表名:子節點在表中的對應的欄位名稱 :上級節點在表中的欄位名稱 db = pymssql.connect( ........charset='GBK') tree = RelationTree() tree.gentree(db,........) tree.drawTree('tree.png')