用Python将mysql数据导出成json的方法
作者:BabyFish13 时间:2024-01-26 09:08:58
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)
来源:https://blog.csdn.net/BabyFish13/article/details/75040144
标签:Python,mysql,json


猜你喜欢
php在linux环境中如何使用redis详解
2023-06-14 23:38:30
python数据分析实战指南之异常值处理
2023-04-19 21:02:18

js类的继承定义与用法分析
2024-04-22 22:34:07
Python中asyncio模块的深入讲解
2022-05-18 22:33:53
SQLSERVER 语句交错引发的死锁问题案例详解
2024-01-15 04:31:24

什么是用户体验优化(UEO)
2008-08-27 19:49:00
MySQL 的启动和连接方式实例分析
2024-01-21 09:06:03

pandas-resample按时间聚合实例
2023-05-26 19:07:50

基于np.arange与np.linspace细微区别(数据溢出问题)
2021-08-29 23:46:25

Python如何实现自带HTTP文件传输服务
2023-01-05 05:04:15

对Python中小整数对象池和大整数对象池的使用详解
2023-02-17 18:13:49
Docker + Nodejs + Kafka + Redis + MySQL搭建简单秒杀环境
2024-01-21 23:22:38

Python常用编译器原理及特点解析
2021-09-04 05:10:11
ASP UTF-8编码下字符串截取和获取长度函数
2011-03-30 10:52:00
使用python实现knn算法
2022-01-26 09:33:45

使用pyecharts1.7进行简单的可视化大全
2022-02-13 05:02:33

利用WSH获取计算机硬件信息、DNS信息等
2008-05-05 13:04:00
解决Python import .pyd 可能遇到路径的问题
2023-06-30 14:33:33

Python科学画图代码分享
2023-08-19 07:06:25

在Docker上部署Python的Flask框架的教程
2023-03-27 02:55:38