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


Posted in Python onAugust 21, 2018

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 相关文章推荐
使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例
Jan 19 Python
python列表去重的二种方法
Feb 14 Python
Python中的ConfigParser模块使用详解
May 04 Python
pycharm远程调试openstack代码
Nov 21 Python
PyQt5每天必学之布局管理
Apr 19 Python
django admin 后台实现三级联动的示例代码
Jun 22 Python
Python DataFrame.groupby()聚合函数,分组级运算
Sep 18 Python
Python函数中不定长参数的写法
Feb 13 Python
pandas DataFrame索引行列的实现
Jun 04 Python
python是否适合网页编程详解
Oct 04 Python
Python with关键字,上下文管理器,@contextmanager文件操作示例
Oct 17 Python
python做接口测试的必要性
Nov 20 Python
windows下python 3.6.4安装配置图文教程
Aug 21 #Python
Python多进程与服务器并发原理及用法实例分析
Aug 21 #Python
Python socket实现的简单通信功能示例
Aug 21 #Python
Python多进程原理与用法分析
Aug 21 #Python
python安装twisted的问题解析
Aug 21 #Python
使用python的pandas库读取csv文件保存至mysql数据库
Aug 20 #Python
Python多线程原理与用法详解
Aug 20 #Python
You might like
用PHP写的基于Memcache的Queue实现代码
2011/11/27 PHP
浅析Apache中RewriteCond规则参数的详细介绍
2013/06/30 PHP
shell脚本作为保证PHP脚本不挂掉的守护进程实例分享
2013/07/15 PHP
ThinkPHP模板IF标签用法详解
2014/07/01 PHP
php中curl和soap方式请求服务超时问题的解决
2018/06/11 PHP
php快速导入大量数据的实例方法
2019/09/23 PHP
for 循环性能比较 提高for循环的效率
2009/03/19 Javascript
js switch case default 的用法示例介绍
2013/10/23 Javascript
Jquery弹出层插件ThickBox的使用方法
2014/12/09 Javascript
轻松创建nodejs服务器(2):nodejs服务器的构成分析
2014/12/18 NodeJs
使用js画图之饼图
2015/01/12 Javascript
关于javascript中dataset的问题小结
2015/11/16 Javascript
jquery ezUI 双击行记录弹窗查看明细的实现方法
2016/06/01 Javascript
浅谈bootstrap源码分析之tab(选项卡)
2016/06/06 Javascript
AngularJs Scope详解及示例代码
2016/09/01 Javascript
实现图片首尾平滑轮播(JS原生方法—节流)
2017/10/17 Javascript
基于vue1和vue2获取dom元素的方法
2018/03/17 Javascript
打通前后端构建一个Vue+Express的开发环境
2018/07/17 Javascript
详解如何构建一个Angular6的第三方npm包
2018/09/07 Javascript
Node.js+ELK日志规范的实现
2019/05/23 Javascript
浅析webpack-bundle-analyzer在vue-cli3中的使用
2019/10/23 Javascript
[05:13]TI4 中国战队 机场出征!!
2014/07/07 DOTA
Python多进程并发(multiprocessing)用法实例详解
2015/06/02 Python
python bmp转换为jpg 并删除原图的方法
2018/10/25 Python
Django shell调试models输出的SQL语句方法
2019/08/29 Python
TensorFlow绘制loss/accuracy曲线的实例
2020/01/21 Python
pytorch  网络参数 weight bias 初始化详解
2020/06/24 Python
解决Keras的自定义lambda层去reshape张量时model保存出错问题
2020/07/01 Python
获取CSDN文章内容并转换为markdown文本的python
2020/09/06 Python
python hmac模块验证客户端的合法性
2020/11/07 Python
生育关怀行动实施方案
2014/03/26 职场文书
单位介绍信格式范文
2015/05/04 职场文书
2016大学迎新欢迎词
2015/09/29 职场文书
图解排序算法之希尔排序Java实现
2021/06/26 Java/Android
Smart 2 车辆代号 HC11 全新谍照曝光
2022/04/21 数码科技
Python循环之while无限迭代
2022/04/30 Python