1、題目要求
將考試文件夾班級成績錄入數據庫,採取不同的方式錄入,通過統計單位時間錄入的學生信息。
2、不專業講解
日常水文,本代碼只使用了一種方式錄入。MySQL只需要創建庫,不需要創建表,自動生成表。
3、項目結構
4、代碼
#!/usr/bin/python
import pandas as pd
from sqlalchemy import create_engine
import time
import os
# TODO:修改成自己的數據庫信息
DB_CONFIG = {
'host': '127.0.0.1',
'port': '3306',
'database': 'score_db',
'user': 'username',
'password': 'password',
'tablename': 'sut_score'
}
def pool_db():
user = DB_CONFIG.get('user')
password = DB_CONFIG.get('password')
host = DB_CONFIG.get('host')
port = DB_CONFIG.get('port')
database = DB_CONFIG.get('database')
return create_engine("mysql+pymysql://"+user+":"+password+"@"+host+":"+port+"/"+database, encoding='utf8')
if __name__ == '__main__':
# xls文件存放相對項目路徑
file_path = './score'
excel_paths = [os.path.join(file_path, f) for f in os.listdir(file_path)]
# 建立數據庫連接
engine = pool_db()
# 獲取開始時間戳
start_time = time.time()
# 遍歷{file_path}目錄下的所有xls文件
for excel_path in excel_paths:
df = pd.read_excel(excel_path)
df.to_sql(DB_CONFIG.get('tablename'),con=engine,if_exists='append',index=False)
# 獲取結束時間戳
end_time = time.time()
# 打印時間戳差值(取4位小數)
time = format(end_time - start_time, '.4f')
print('用時約 ' + str(time) + ' 秒')
5、運行結果
控制檯輸出