Python 输出JSON对象数组&写入数据到MySQL

准备数据,放到列表中

import re
input = open('C:\\Users\\Administrator\\Desktop\\e.txt','r')
text=input.read()
list = re.split('\n',text)
location = []
for element in list:
    location.append([re.split('\|',element)[3],re.split('\|',element)[4]])

输出JSON对象数组

import json
list=[]
for e in location:
    info={}
    info["lat"]=e[0]
    info["lng"]=e[1]
    list.append(info)
jsonStr = json.dumps(list)  
print "jsonStr:",jsonStr  

写入数据到MySQL

创建表,设置id自动递增

create table Latitude(id int auto_increment primary key,
lat double , lng double);
import MySQLdb
db = MySQLdb.connect("master", "root", "root", "TDUserTrace", charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()

for e in location:
    sql = "INSERT INTO Latitude(lat,lng) \
    VALUES ('%.20f','%.20f')" % \
    (float(e[0]),float(e[1]))
    try:
    # 执行sql语句
        cursor.execute(sql)
    # 提交到数据库执行
        db.commit()
    except:
    # Rollback in case there is any error
        print "wrong"
        db.rollback()
try:
    sql = "SELECT * FROM Latitude"
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        print row[0]
except:
    print "Error: unable to fecth data"

你可能感兴趣的:(python,python,json,mysql)