Python连接SQL Server生成JSON文件实战示例
本文详细介绍如何使用Python连接SQL Server数据库,通过mssqlhelper库执行查询,并将省、市、区三级行政区划数据递归写入JSON文件。文章提供完整Python代码示例,展示如何构建嵌套JSON结构并处理文件IO,同时推荐多款实用的在线JSON格式化工具以辅助开发。
本文通过一个具体实例,演示如何利用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. 生成结果预览

此外,推荐以下几款实用的JSON在线处理工具供参考:
在线JSON代码检验、格式化与美化工具: http://tools.jb51.net/code/json
JSON在线格式化工具: http://tools.jb51.net/code/jsonformat
在线XML与JSON互转工具: http://tools.jb51.net/code/xmljson
JSON代码在线格式化、美化、压缩、编辑及转换工具: http://tools.jb51.net/code/jsoncodeformat
在线JSON压缩与转义处理工具: http://tools.jb51.net/code/json_yasuo_trans
如需了解更多Python相关知识,建议查阅本站专题:《Python操作json技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》。
希望本文提供的Python程序设计示例能对读者有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













