日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > 数据库 >内容正文

数据库

python抓取数据库数据封装成json_用Python将mysql数据导出成json的方法

發(fā)布時(shí)間:2025/3/20 数据库 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python抓取数据库数据封装成json_用Python将mysql数据导出成json的方法 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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 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ù)導(dǎo)出成json的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

總結(jié)

以上是生活随笔為你收集整理的python抓取数据库数据封装成json_用Python将mysql数据导出成json的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。