用Python将mysql数据导出成json的方法

yipeiwu_com5年前Python基础

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设计】。

相关文章

python实现windows倒计时锁屏功能

python实现windows倒计时锁屏功能 # 倒计时锁屏 import time from ctypes import * def closewindows(closetime)...

python中嵌套函数的实操步骤

python中嵌套函数的实操步骤

在python中如何嵌套函数? 首先打开python编辑器并且写上注释的内容。 然后定义一个函数addstr 在addstr函数里面写上内容,内容是写入文件内容。 新建第二个函数...

Python实现将json文件中向量写入Excel的方法

本文实例讲述了Python实现将json文件中向量写入Excel的方法。分享给大家供大家参考,具体如下: 有一个需要是将已经向量化的页面的数据中的向量写入Excel中用于展示,工作很简单...

解读python logging模块的使用方法

1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点:...

Python基于更相减损术实现求解最大公约数的方法

Python基于更相减损术实现求解最大公约数的方法

本文实例讲述了Python基于更相减损术实现求解最大公约数的方法。分享给大家供大家参考,具体如下: 先从网上摘录一段算法的描述如下: 更相减损法:也叫 更相减损术,是出自《 九章算术》的...