#!/usr/bin/env python
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import pymysql
# 連接數(shù)據(jù)庫
conn = pymysql.connect(
host='localhost',
user='root',
passwd='root',
db='thinkcmf',
charset='utf8',
use_unicode=True
)
# 建立游標(biāo)cursor
cursor = conn.cursor()
# 執(zhí)行查
cursor.execute("SELECT * FROM hy_area")
# 查詢數(shù)據(jù)庫多條數(shù)據(jù)
result = cursor.fetchall()
fields = cursor.description
cursor.close()
conn.close()
# 定義字段名的列表
column_list = []
for i in fields:
# 提取字段名,追加到列表中
column_list.append(i[0])
# print(column_list)
# ['Id', 'name', 'password', 'birthplace']
# 打開輸出結(jié)果文件
with open('/storage/emulated/0/經(jīng)緯度/json.json', 'w+') as f:
# 一次循環(huán),row代表一行,row以元組的形式顯示
for row in result:
# 定義Python 字典
data = {}
# 將row中的每個元素,追加到字典中。
for i in range(len(column_list)):
data[column_list[i]] = row[i]
# data[column_list[0]] = row[0]
# # Python字段格式 和json字段格式轉(zhuǎn)換
# data[column_list[1]] = str(row[1])
# data[column_list[2]] = str(row[2])
# data[column_list[3]] = str(row[3])
# Python的dict --轉(zhuǎn)換成----> json的object
jsondata = json.dumps(data, ensure_ascii=False)
# 寫入文件
f.write(jsondata + ',' + '\n')
f.close()
?
? 版權(quán)聲明
THE END







- 最新
- 最熱
只看作者