本文實(shí)例講述了Python SQL查詢并生成json文件操作。分享給大家供大家參考,具體如下:
1. 數(shù)據(jù)準(zhǔn)備
SQL數(shù)據(jù)點(diǎn)擊此處本站下載。
2. python代碼
import datetime import osimport mssqlhelperms = mssqlhelper.MSSQL(host="192.168.0.108", user="sa", pwd="sa", db="ComPrject")def getAreas(cityid): arealist=ms.ExecQuery("select *From dbo.areas where cityid='%s' " % cityid) return arealistdef getCity(provinces): citylist=ms.ExecQuery("select *From dbo.cities where provinceid='%s'" % provinces) return citylistdef getProvinces(): provlist=ms.ExecQuery("select *From dbo.provinces") return provlistdef createFileJson(): date=datetime.datetime.now().strftime('%Y-%m-%d') path=date+'-provinces.json' return pathdef writeJson(path): provlist=getProvinces() with open(path,"w+",encoding="utf-8") as f: f.write("[") lp = 0 for p in provlist: if lp>0: f.write(",/n") else: f.write("/n") f.write("{/n") f.write('"Code":"%s"/n'% p[1]) f.write(',"Name":"%s"/n'% p[2]) f.write(',Nodes:[/n') citylist=getCity(p[1]) lc = 0 for c in citylist: if lc>0: f.write("/t,/n") else: f.write("/n") f.write("/t{/n") f.write('/t"Code":"%s"/n'% c[1]) f.write('/t,"Name":"%s"/n'% c[2]) f.write('/t,Nodes:[/n') arealist = getAreas(c[1]) la = 0 for a in arealist: if la>0: f.write("/t/t,/n") else: f.write("/n") f.write("/t/t{/n") f.write('/t/t"Code":"%s"/n'% a[1]) f.write('/t/t,"Name":"%s"/n'% a[2]) f.write("/t/t}/n") la += 1 f.write("/t]/n") f.write("/t}/n") lc += 1 f.write("]/n") f.write("}/n") lp += 1 f.write("]/n")if __name__ == '__main__': path=createFileJson() writeJson(path)3.生成預(yù)覽
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選