循環建立表,而且建立主鍵、外鍵
import pandas as pd from sqlalchemy import create_engine from sqlalchemy.types import NVARCHAR, Float, Integer def pd2sql(): """ to_sql目前只支持兩類mysql引擎一個是sqlalchemy和sqlliet3 :return: """ # 初始化數據庫鏈接,使用pymysql模塊 # MySQL的用戶:root, 密碼:147369, 端口:3306,數據庫:mydb # ?charset=utf8 指定數據庫編碼 engine = create_engine('mysql+pymysql://root:@localhost:3306/pandas2mysql?charset=utf8') conn = engine.connect() for i in range(1, 10): # 指定字段的數據類型 dtypedict = { 'index_code': NVARCHAR(length=255), 'date': NVARCHAR(length=255), 'open': NVARCHAR(length=255), 'close': NVARCHAR(length=255), 'low': NVARCHAR(length=255), 'high': NVARCHAR(length=255), 'volume': NVARCHAR(length=255), 'money': NVARCHAR(length=255), 'change': NVARCHAR(length=255) } csv_path = r'E:\data\yucezhe\trading-data-push.20190201\2019-02-01 index data.csv' # 讀取本地CSV文件 df = pd.read_csv(csv_path).head() # 將DataFrame儲存爲MySQL中的數據表,不儲存index列 df.to_sql(f'csv_table{i}', engine, if_exists='replace', index=False, dtype=dtypedict) # 執行原生sql語句 # 設置主鍵 conn.execute(f"alter table csv_table{i} add constraint p_key primary key (index_code)") # 從表設置外鍵 if i%2 == 0: conn.execute( f"alter table csv_table{i-1} add foreign key (index_code) references csv_table{i}(index_code)") print(f"Write to MySQL successfully! ---- csv_table{i}") engine.dispose() pd2sql() # 對已存在的表作主鍵:alter table csv_short1 add constraint p_key primary key (index_code); # 對已存在的表作外鍵:alter table csv_short1 add foreign key (index_code) references csv_short2(index_code); # 內鏈接查詢:select * from a,b where a.x = b.x