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

本文介绍了一个Python脚本,用于将Mysql数据库中的数据导出为Json格式。脚本通过执行指定的SQL查询从数据库中获取数据,并使用MySQLdb和json库将结果保存到JSON文件中。导出过程包括设置数据库连接、执行查询、处理结果并写入文件。示例代码展示了如何使用该脚本导出特定表的数据。
摘要由CSDN通过智能技术生成

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的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值