资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

如何使用Python将mysql数据导出成json-创新互联

这篇文章将为大家详细讲解有关如何使用Python将mysql数据导出成json,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

公司专注于为企业提供网站建设、网站制作、微信公众号开发、商城开发,微信小程序定制开发,软件按需定制等一站式互联网企业服务。凭借多年丰富的经验,我们会仔细了解各客户的需求而做出多方面的分析、设计、整合,为客户设计出具风格及创意性的商业解决方案,创新互联公司更提供一系列网站制作和网站推广的服务。python有哪些常用库

python常用的库:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。

1、相关说明

此脚本可以将Mysql的数据导出成Json格式,导出的内容可以进行select查询确定。

数据传入参数有:dbConfigName, selectSql, jsonPath, fileName。

依赖的库有:MySQLdb、json,尤其MySQLdb需要事先安装好。

2、Python脚本及测试示例

/Users/nisj/PycharmProjects/BiDataProc/oldPythonBak/mysqlData2json.py

# -*- coding=utf-8 -*-
import MySQLdb
import warnings
import datetime
import sys
import json
reload(sys)
sys.setdefaultencoding('utf8')
 
warnings.filterwarnings("ignore")
 
mysqlDb_config = {
  'host': 'MysqlHostIp',
  'user': 'MysqlUser',
  'passwd': 'MysqlPass',
  'port': 50512,
  'db': 'Tv_event'
}
 
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
 
def getDB(dbConfigName):
  dbConfig = eval(dbConfigName)
  try:
    conn = MySQLdb.connect(host=dbConfig['host'], user=dbConfig['user'], passwd=dbConfig['passwd'],
                port=dbConfig['port'])
    conn.autocommit(True)
    curr = conn.cursor()
    curr.execute("SET NAMES utf8");
    curr.execute("USE %s" % dbConfig['db']);
 
    return conn, curr
  except MySQLdb.Error, e:
    print "Mysql Error %d: %s" % (e.args[0], e.args[1])
    return None, None
 
def mysql2json(dbConfigName, selectSql, jsonPath, fileName):
  conn, curr = getDB(dbConfigName)
  curr.execute(selectSql)
  datas = curr.fetchall()
  fields = curr.description
 
  column_list = []
  for field in fields:
    column_list.append(field[0])
 
  with open('{jsonPath}{fileName}.json'.format(jsonPath=jsonPath, fileName=fileName), 'w+') as f:
    for row in datas:
      result = {}
      for fieldIndex in range(0, len(column_list)):
        result[column_list[fieldIndex]] = str(row[fieldIndex])
      jsondata=json.dumps(result, ensure_ascii=False)
      f.write(jsondata + '\n')
  f.close()
 
  curr.close()
  conn.close()
 
# Batch Test
dbConfigName = 'mysqlDb_config'
selectSql = "SELECT uid,name,phone_num,qq,area,created_time FROM match_apply where match_id = 83 order by created_time desc;"
jsonPath = '/Users/nisj/Desktop/'
fileName = 'mysql2json'
mysql2json(dbConfigName, selectSql, jsonPath, fileName)

关于“如何使用Python将mysql数据导出成json”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。


标题名称:如何使用Python将mysql数据导出成json-创新互联
浏览地址:http://cdkjz.cn/article/djjhps.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220