Python Tip:Python3如何獲取MySQL資料?
問題背景:資料存放在SQL/">MySQL裡面,在資料庫裡面查詢發現有個欄位的資料是JSON格式,不方便進行後續的操作,比方說:統計分析,特徵提取等。所以想把這個欄位裡面的JSON格式資料進行解析,解析成功後,然後把以結構化表的形式存放到MySQL資料庫。
解決方案:首先通過Python3連線MySQL,然後獲取MySQL資料集,接下來利用Python的相應庫解析JSON格式資料,最後把解析好資料放到資料框,並回存到MySQL資料庫。
Python3連線MySQL程式碼片段
import pymysql # 連線資料庫 conn = pymysql.connect( host = "your host", port = your port, user = "your user name", passwd = "your user passwd", db="your db")
Python3獲取MySQL資料程式碼片段
# 建立遊標 cur = conn.cursor() # 查詢t_test表的所需欄位資料 cur.execute("select user_id, file_id from t_test") # 獲取t_test所有資料 result = cur.fetchall() #print(result) import pandas as pd df_result = pd.DataFrame(list(result), columns = ["user_id", "file_id"]) print(df_result.shape) print(df_result.head())
完整程式碼
import pymysql import pandas as pd # 連線資料庫 conn = pymysql.connect( host = "your host", port = your port, user = "your user name", passwd = "your user passwd", db="your db") # 建立遊標 cur = conn.cursor() # 查詢t_test表的所需欄位資料 cur.execute("select user_id, file_id from t_test") # 獲取t_test所有資料 result = cur.fetchall() #print(result) df_result = pd.DataFrame(list(result), columns = ["user_id", "file_id"]) print(df_result.shape) print(df_result.head())
版權宣告:作者保留權利,嚴禁修改,轉載請註明原文連結。
資料人網是資料人學習、交流和分享的平臺http://shujuren.org 。專注於從資料中學習到有用知識。 平臺的理念:人人投稿,知識共享;人人分析,洞見驅動;智慧聚合,普惠人人。 您在資料人網平臺,可以1)學習資料知識;2)建立資料部落格;3)認識資料朋友;4)尋找資料工作;5)找到其它與資料相關的乾貨。 我們努力堅持做原創,聚合和分享優質的省時的資料知識! 我們都是資料人,資料是有價值的,堅定不移地實現從資料到商業價值的轉換!