如何在Python中使用SQL查询并生成json文件

  介绍

本篇文章为大家展示了如何在Python中使用SQL查询并生成json文件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

Python是什么意思

Python是一种跨平台的,具有解释性,编译性,互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。

<强> 1。数据准备

SQL数据点击此处<强>本站下载

<强> 2。python代码

import  datetime    import 操作系统   import  mssqlhelper   小姐=,mssqlhelper.MSSQL(主机=?92.168.0.108",,用户=皊a",, pwd=皊a",, db=癈omPrject")   def  getAreas (cityid):   arealist才能=ms.ExecQuery (“select  *得到dbo.areas  where  cityid=& # 39; % & # 39;,,, %, cityid)   return  arealist才能   def  getCity(省):   citylist才能=ms.ExecQuery (“select  *得到dbo.cities  where  provinceid=& # 39; % & # 39;“, %,省)   return  citylist才能   def  getProvinces ():   provlist才能=ms.ExecQuery(得到dbo.provinces"获“select  *)   return  provlist才能   def  createFileJson ():   日期才能=datetime.datetime.now () .strftime (& # 39; Y - % - % d % # 39;)   路径才能=日期+ & # 39;-provinces.json& # 39;   return 才能;路径   def  writeJson(路径):   provlist才能=getProvinces ()   with 才能;开放(路径,“w +“编码=皍tf-8"), as  f:   ,,,f.write (“[“)   ,,,lp =0   ,,,for  p 拷贝provlist:   ,,,,,if  lp> 0:   ,,,,,,,f.write (“\ n")   ,,,,,其他的:   ,,,,,,,f.write (“\ n")   ,,,,,f.write (“{\ n")   ,,,,,f.write (& # 39;“Code":“% s" \ n # 39; %, p [1])   ,,,,,f.write (& # 39;“Name":“% s" \ n # 39; %, p [2])   ,,,,,f.write(& # 39;节点:[\ n # 39;)   ,,,,,citylist=getCity (p [1])   ,,,,,lc =0   ,,,,,for  c 拷贝citylist:   ,,,,,,,if  lc> 0:   ,,,,,,,,,f.write (“\ t \ n")   ,,,,,,,其他的:   ,,,,,,,,,f.write (“\ n")   ,,,,,,,f.write (“\ t {\ n")   ,,,,,,,f.write (& # 39; \ t" Code":“% s" \ n # 39; %, c [1])   ,,,,,,,f.write (& # 39; \ t,“Name":“% s" \ n # 39; %, c [2])   ,,,,,,,f.write (& # 39; \ t,节点:[\ n # 39;)   ,,,,,,,arealist =, getAreas (c [1])   ,,,,,,,la =0   ,,,,,,,for  a 拷贝arealist:   ,,,,,,,,,if  la> 0:   ,,,,,,,,,,,f.write (“\ t \ \ n")   ,,,,,,,,,其他的:   ,,,,,,,,,,,f.write (“\ n")   ,,,,,,,,,f.write (“\ t \ {\ n")   ,,,,,,,,,f.write (& # 39; \ t \ t" Code":“% s" \ n # 39; %, [1])   ,,,,,,,,,f.write (& # 39; \ t \ t,“Name":“% s" \ n # 39; %, [2])   ,,,,,,,,,f.write (“\ 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__ ==, & # 39; __main__ # 39;:   路径才能=createFileJson ()   writeJson才能(路径)

<强> 3。生成预览

如何在Python中使用SQL查询并生成json文件

上述内容就是如何在Python中使用SQL查询并生成json文件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。

如何在Python中使用SQL查询并生成json文件