數據處理步驟:
1、Pandas讀取數據(如:excel、csv等)
2、對數據做過濾、統計分析
3、Pandas將數據存儲到MySQL,用於Web頁面的頁面顯示,或是對后序進一步的SQL分析
(處理后的數據)
步驟一:准備數據
import pandas as pd df = pd.read_excel('C:/Users/xhl/Desktop/input/class.xlsx') #為索引加上名稱為id,以便入庫成為主鍵 df.index.name = 'id'
步驟2:創建sqlalchemy對象連接MySQL
SQLAlchemy是Python中的ORM框架(Object-Relation Mapping),把關系數據庫的表映射到對象上
安裝sqlalchemy前需要安裝Python依賴庫,即pip install mysql-connector-python
>>>from sqlalchemy import create_engine #mysql表示連接MySQL數據庫 #mysqlconnector表示使用的庫,就是pip install mysql-connector-python中的 #root:MySQL的用戶名,123456表示密碼,后面分別是表示連接至本地,端口號,數據庫名 >>>engine = create_engine("mysql+mysqlconnector://root:123456@127.0.0.1:3306/testdb",echo=False)
方法1:當數據表不存在時,每次覆蓋整個表
fetchall():
返回多個元組,即返回多個記錄(rows),如果沒有結果 則返回 () 需要注明:在MySQL中是NULL,而在Python中則是None
#每次運行會drop table,新建表 #name屬性表示表的名字,if_exists表示若表存在就替代 >>>df.to_sql(name = 'class',con = engine,if_exists="replace") # 查看表結構 >>>print(engine.execute("show create table class").first()[1]) CREATE TABLE `class` ( `id` bigint(20) DEFAULT NULL, `class` text COLLATE utf8_bin, `sex` text COLLATE utf8_bin, `score_math` bigint(20) DEFAULT NULL, `score_music` bigint(20) DEFAULT NULL, KEY `ix_class_id` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin #查看一共多少條 >>>print(engine.execute("select count(1) from class").first()) (9,) #查看數據前3條 >>>engine.execute("select * from class limit 3").fetchall() [(0, b'A', b'male', 95, 79), (1, b'A', b'female', 96, 90), (2, b'B', b'female', 85, 85)]
方法2:當數據表存在時,每次新增數據
>>>df_new = df.loc[:2] >>>df_new.to_sql(name='class',con=engine,if_exists='append') >>>engine.execute("select * from class where id<=2").fetchall() [(0, b'A', b'male', 95, 79), (0, b'A', b'male', 95, 79), (1, b'A', b'female', 96, 90), (1, b'A', b'female', 96, 90), (2, b'B', b'female', 85, 85), (2, b'B', b'female', 85, 85)]
通過上述可以發現,使用append會增加,同一條數據會有冗余
問題解決:先通過數據KEY刪除舊數據
>>>for id in df_new.index: ... #先刪除要新增的數據 ... delete_sql = f"delete from class student where id={id}" ... print(delete_sql) ... engine.execute(delete_sql) delete from class student where id=0 delete from class student where id=1 delete from class student where id=2 #刪除數據 >>>engine.execute("select * from class where id<=2").fetchall() [] >>>engine.execute('select count(1) from class').first() (6,) #新增至數據表中 >>>df_new.to_sql(name = 'class',con = engine,if_exists = "append") >>>engine.execute("select * from class where id<=2").fetchall() [(0, b'A', b'male', 95, 79), (1, b'A', b'female', 96, 90), (2, b'B', b'female', 85, 85)] >>>engine.execute("select count(1) from class ").first() (9,)