用python在後端將資料寫入到資料庫並讀取
阿新 • • 發佈:2018-11-09
用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:[email protected]: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)
讀取:
# -*- coding: utf-8 -*- # 匯入必要模組 import pandas as pd from sqlalchemy import create_engine # 初始化資料庫連線,使用pymysql模組 # MySQL的使用者:root, 密碼:147369, 埠:3306,資料庫:mydb engine = create_engine('mysql+pymysql://root:[email protected]:3306/python1') # 查詢語句,選出employee表中的所有資料 sql = ''' select * from student; ''' # read_sql_query的兩個引數: sql語句, 資料庫連線 df = pd.read_sql_query(sql, engine) # 輸出employee表的查詢結果 print(df.shape)