国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

用Python將mysql數(shù)據(jù)導(dǎo)出成json的方法

2020-01-04 14:40:32
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

1、相關(guān)說(shuō)明

腳本可以將Mysql的數(shù)據(jù)導(dǎo)出成Json格式,導(dǎo)出的內(nèi)容可以進(jìn)行select查詢確定。

數(shù)據(jù)傳入?yún)?shù)有:dbConfigName, selectSql, jsonPath, fileName。

依賴的庫(kù)有:MySQLdb、json,尤其MySQLdb需要事先安裝好。

2、Python腳本及測(cè)試示例

/Users/nisj/PycharmProjects/BiDataProc/oldPythonBak/mysqlData2json.py

# -*- coding=utf-8 -*-import MySQLdbimport warningsimport datetimeimport sysimport jsonreload(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 TestdbConfigName = '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ù)導(dǎo)出成json的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持VEVB武林網(wǎng)。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到python教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 句容市| 五莲县| 大竹县| 合川市| 抚州市| 琼海市| 江华| 新野县| 砚山县| 松原市| 黎川县| 福海县| 三都| 吴旗县| 淮滨县| 梁山县| 汾阳市| 中西区| 娄底市| 泗水县| 佛坪县| 甘肃省| 新晃| 建瓯市| 班玛县| 民勤县| 七台河市| 祁门县| 肥城市| 彭水| 武义县| 浦东新区| 武夷山市| 十堰市| 丰宁| 宜丰县| 宜都市| 柳江县| 布尔津县| 裕民县| 辰溪县|