用python在後端將數據寫入到數據庫:python
# coding:utf-8 import pandas as pd from sqlalchemy import create_engine # 初始化數據庫鏈接,使用pymysql模塊 # MySQL的用戶:root, 密碼:147369, 端口:3306,數據庫:mydb engine = create_engine('mysql+pymysql://root:123456@localhost:3306/python1') import numpy as np import datetime start = datetime.datetime.now().strftime('%Y-%m-%d') end = (datetime.datetime.now()+datetime.timedelta(days=100)).strftime('%Y-%m-%d') # 新建pandas中的DataFrame, 只有id,num兩列 df = pd.DataFrame(data=np.random.randint(-100,100,(100,100)),index=pd.date_range('2018-1-1',periods=100,dtype='datetime64[ns]', freq='D'),columns=None,dtype=int) print(df.shape) # 將新建的DataFrame儲存爲MySQL中的數據表,不儲存index列 df.to_sql('data', engine, if_exists='append',index= True)
讀取:mysql
# -*- coding: utf-8 -*- # 導入必要模塊 import pandas as pd from sqlalchemy import create_engine # 初始化數據庫鏈接,使用pymysql模塊 # MySQL的用戶:root, 密碼:147369, 端口:3306,數據庫:mydb engine = create_engine('mysql+pymysql://root:123456@localhost:3306/python1') # 查詢語句,選出employee表中的全部數據 sql = ''' select * from student; ''' # read_sql_query的兩個參數: sql語句, 數據庫鏈接 df = pd.read_sql_query(sql, engine) # 輸出employee表的查詢結果 print(df.shape)