mysql数据库生成json_Python3实现 将MySQL数据库中的记录生成JSON数据
思路:首先連接MYSQL數(shù)據(jù)庫,將查詢到的數(shù)據(jù)存放到字典中,然年將每個組裝好的字典放到List中
調(diào)用json.dumps(jsonData, ensure_ascii=False)方法,生成JSON數(shù)據(jù)并返回。
MySQLData2Json.py
在手機上的效果:
import json, MySQLdb
import io
import sys
import urllib.request
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
'''
Create on 2019-08-12
@author:Philtellcy
@function:Read Data from mysql database transform json format
'''
def Table2Json():
try:
# 連接數(shù)據(jù)庫
conn = MySQLdb.connect(host='localhost', user='root',
passwd='root', db='suibian',charset='utf8')
cur = conn.cursor()
sql = "select * from newstitle"
cur.execute(sql)
result = cur.fetchall()
cur.close()
jsonData = []
# 循環(huán)讀取元組數(shù)據(jù)
print("讀到了數(shù)據(jù)")
for row in result:
data = {}
data['NewsID'] = str(row[0])
data['Title'] = str(row[1])
data['DescCn'] = str(row[2])
data['DescJp'] = str(row[3])
data['Title_ip'] = str(row[4])
data['Title_cn'] = row[5]
print(str(row[5]),row[5],data['Title_cn'])
data['Category'] = str(row[6])
data['TopicId'] = str(row[7])
data['Sound'] = str(row[8])
data['Url'] = str(row[9])
data['Pic'] = str(row[10])
data['PicDesc'] = str(row[11])
data['CreatTime'] = str(row[12])
data['PublishTime'] = str(row[13])
data['ReadCount'] = str(row[14])
data['HotFlag'] = str(row[15])
data['Flag'] = str(row[16])
data['WordCount'] = str(row[17])
data['HardWeight'] = str(row[18])
data['TFlag'] = str(row[19])
data['uid'] = str(row[20])
data['auid'] = str(row[21])
data['groupid'] = str(row[22])
data['Likes'] = str(row[23])
data['DisLikes'] = str(row[24])
data['newsfrom'] = str(row[25])
data['VFlag'] = str(row[26])
jsonData.append(data)
jsondatar = json.dumps(jsonData, ensure_ascii=False)
return jsondatar[1:len(jsondatar) - 1]
print("連接成功")
except Exception as e:
print('MySQL connect fail ',e)
if __name__ == '__main__':
jsonData = Table2Json()
print("轉(zhuǎn)換成json的數(shù)據(jù)",jsonData)
# 將數(shù)據(jù)存放到本地
f = open('D:\getuidata.txt', 'w+',encoding='utf-8')
f.write(jsonData)
f.close()
總結(jié)
以上是生活随笔為你收集整理的mysql数据库生成json_Python3实现 将MySQL数据库中的记录生成JSON数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 奥美拉唑的副作用有哪些
- 下一篇: mysql按字段值排序_mysql按字段