1. 程式人生 > >Python 輸出JSON物件陣列&寫入資料到MySQL

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"