脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python SQL查询并生成json文件操作示例

Python SQL查询并生成json文件操作示例

2021-03-28 00:17sulin Python

这篇文章主要介绍了Python SQL查询并生成json文件操作,涉及Python基于mssqlhelper模块进行mysql数据库查询与json格式文件生成相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python SQL查询并生成json文件操作。分享给大家供大家参考,具体如下:

1. 数据准备

SQL数据点击此处本站下载

2. python代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import datetime
import os
import mssqlhelper
ms = 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 arealist
def getCity(provinces):
  citylist=ms.ExecQuery("select *From dbo.cities where provinceid='%s'" % provinces)
  return citylist
def getProvinces():
  provlist=ms.ExecQuery("select *From dbo.provinces")
  return provlist
def createFileJson():
  date=datetime.datetime.now().strftime('%Y-%m-%d')
  path=date+'-provinces.json'
  return path
def 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.生成预览

Python SQL查询并生成json文件操作示例

 

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://www.cnblogs.com/linsu/p/8808914.html

延伸 · 阅读

精彩推荐