行业递归

#上下游递归寻找

import csv
import psycopg2
class IO_rw(object):

def __init__(self):

self.conn = psycopg2.connect(database="postgres", user="postgres", password="123456", host="127.0.0.1", port="5432")
self.cur = self.conn.cursor()
self.read = []
self.datadict = {}
#
def process_item(self):

self.cur.execute("select id,name,pid from bjzs_big_data.baoji_industry_level where pid = 0")
rows = self.cur.fetchall()

#拿到所有的一级分类
dict = {}
for row in rows:
row = list(row)
dict[row[0]] = row[1]
li = list(dict.items())
return li

#下游
def sql_dowm(self,i):

self.cur.execute("select downid from bjzs_big_data.baoji_industry_chain where upid = {}".format(i))
rows = self.cur.fetchall()
downList = []
for row in rows:
downList.append(row[0])
return downList

#上游
def sql_up(self,i):
self.cur.execute("select upid from bjzs_big_data.baoji_industry_chain where downid = {}".format(i))
rows = self.cur.fetchall()
downList = []
for row in rows:
downList.append(row[0])
return downList


def getAllDowm(self, id):
temp = {}

#把当前的id放在 全局的read里面。用于纺织重新查找
self.read.append(id)

#查找它的下游
downList = self.sql_dowm(id)
#self.getName(downList)

#查找它的上游
upList = self.sql_up(id)
#self.getName(upList)

temp['up'] = upList
temp['down'] = downList

self.datadict[id] = temp

#判断拿到的 id 是否存在
for down in downList:
self.getName(down)
if down in self.read:
pass
else:
downList = self.getAllDowm(down)

for up in upList:
self.getName(up)
if up in self.read:
pass
else:
downList = self.getAllDowm(up)

def getName(self,id):
if id == '':
return 0
self.cur.execute("select name from bjzs_big_data.baoji_industry_level where id = {}".format(id))
rows = self.cur.fetchall()



if __name__ == '__main__':
r = IO_rw()

li = r.process_item()

for i in li:
r.getAllDowm(i[0])
print(r.datadict)
r.datadict = {}
r.cur.close()
r.conn.close()

原文地址:https://www.cnblogs.com/yuanjia8888/p/10156570.html