您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關如何使用Python將mysql數(shù)據(jù)導出成json,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
python常用的庫:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。
1、相關說明
此腳本可以將Mysql的數(shù)據(jù)導出成Json格式,導出的內(nèi)容可以進行select查詢確定。
數(shù)據(jù)傳入?yún)?shù)有: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數(shù)據(jù)導出成json”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。