之前弄數據庫的時候, 測試excel導mysql, 中間用pandas 處理后再入庫. 直接上代碼, 此種有真意, 盡在不言中.
1 #!/usr/bin/env python 2 # coding: utf-8 3 # author: chenjie131@ke.com 4 5 ''' 6 應用場景: 7 將excel等存儲的數據導入到 Mysql, 適用於追加表, 或者追加數據. 8 9 1. 數據庫表已存在, 可在需表后面添加數據. 10 2. 數據庫表不存在, 導入時直接創建表在數據庫中. 11 3. 特點: 12 3.1 這里用pandas.to_sql()方法, 以塊的方式導入效率高, 10000行100列的表,2.5s 導完. 13 3.2 替代品,sql方式可參考load data local .... 14 3.3 缺點是如果表存在, 且設置主鍵約束, 就不適用 15 16 17 ''' 18 19 import pandas as pd 20 from sqlalchemy import create_engine 21 22 23 文件路徑 = "C:\\Users\beike\\Desktop\\8月帶看明細8.15.xls" 24 25 # 1. 讀取excel, sheet_name: 默認讀取Sheet1,按需指定 26 table = pd.read_excel(文件路徑, sheet_name="明細") 27 28 29 # 2. 連接MySql數據庫, //后的參數為: 用戶名, 密碼, 主機, 數據庫名 30 engine = create_engine("mysql+pymysql://zmj:123456@192.168.6.81:3306/new_house") 31 32 # 3. 連接測試 33 try: 34 pd.read_sql("show tables;", con=engine); print("connect successfully!") 35 except Exception as error: 36 print("connect fail! because of :", error) 37 38 # 4. to_sql()方法插入數據, 更多細節自行查文檔 39 40 # 參數1: 表的名字,建議不要用中文 41 # con: 之前創建的連接對象 42 # if_exists: 43 # "replace": 如果傳入的表名在庫里存在, 則會刪掉該表, 重新創建 44 # "append": 如果傳入的表名在庫里存在, 則會追加數據, 注意字段順序一致, 注意當有主鍵約束則易報錯 45 try: 46 table.to_sql("測試表", con=engine, index=False, if_exists="replace"); 47 48 print("insert successfully!") 49 except Exception as error: print("insert fail! because of:", error) 50 51 52 print("##"*20) 53 print("done!")