欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-25 21:43:45
本文实例讲述了python sql查询并生成json文件操作。分享给大家供大家参考,具体如下: 1. 数据准备 sql数据点击此处本站下载。 2. python代码...

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

1. 数据准备

sql数据点击此处本站下载

2. python代码

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文件操作示例

ps:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线json代码检验、检验、美化、格式化工具:

json在线格式化工具:

在线xml/json互相转换工具:

json代码在线格式化/美化/压缩/编辑/转换工具:

在线json压缩/转义工具:

更多python相关内容感兴趣的读者可查看本站专题:《python操作json技巧总结》、《python编码操作技巧总结》、《python数据结构与算法教程》、《python函数使用技巧总结》、《python字符串操作技巧汇总》、《python入门与进阶经典教程》及《python文件与目录操作技巧汇总

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

上一篇:

下一篇: