近期工作遇到了excel數(shù)據(jù)灌入數(shù)據(jù)庫表的任務(wù),無聊整理一下實(shí)現(xiàn)方法:
System.out.println("=======分割線======");
1、使用數(shù)據(jù)庫管理工具
首先是使用工具來完成,常見的比較成熟的數(shù)據(jù)庫管理軟件都有這個(gè)功能,MySQL Workbench、Navict、DataGrip、DBeaver。這里拿DBeaver舉例:
-
將excel另存為csv格式,選擇編碼為UTF-8
-
右鍵要導(dǎo)入的表,選擇導(dǎo)入數(shù)據(jù)
-
選擇csv做為數(shù)據(jù)源,點(diǎn)擊下一步
-
點(diǎn)擊選擇csv文件
-
下拉選擇excel字段與MySQL字段映射關(guān)系
-
點(diǎn)擊開始,F(xiàn)5刷新即可看到新數(shù)據(jù)
2、使用SQL
- excel轉(zhuǎn)csv,逗號(hào)分隔,utf-8格式
- 連接數(shù)據(jù)庫執(zhí)行以下SQL
load data local infile 'd:/test.csv'
into table testDB.t_book
fields terminated by ',';
# 注意這時(shí)excel中列的順序和表的字段順序是剛好對(duì)應(yīng)的
- 注意當(dāng)excel和table字段不對(duì)應(yīng)時(shí),按照csv文件表頭順序?qū)憇ql
load data local infile 'd:/test.csv'
into table testDB.t_book
fields terminated by ','
lines terminated by '\r\n'
ignore 1 lines (name,description);
# 即csv文件的第一列給數(shù)據(jù)庫表的name字段,第二列給表的description字段
# 其余字段不管
比如我excel只有name和description兩列數(shù)據(jù),而庫表中要四個(gè)字段,只管按csv的順序分給表中的字段即可,其余字段沒有就空著,不用管。
有的可視化數(shù)據(jù)庫連接工具不支持load data local infile指令,換個(gè)命令行窗口執(zhí)行SQL就行。
3、使用腳本
import pymysql #PyMySQL是在 Python3.x 版本中用于連接 MySQL 服務(wù)器的一個(gè)庫
import pandas as pd #Pandas是Python的一個(gè)數(shù)據(jù)分析包 導(dǎo)入panda命名為pd
from sqlalchemy import create_engine # 導(dǎo)入引擎
file = r'd:/t_test.xlsx' #文件
df = pd.read_excel(file) #讀文件
# 連接數(shù)據(jù)庫
engine = create_engine("mysql+mysqlconnector://root:qwe123@localhost:3306/testDB")
df.to_sql('t_book',con=engine,if_exists='replace',index=False) #導(dǎo)入數(shù)據(jù)庫,如果存在就替換
代碼注釋(參數(shù)):文章來源:http://www.zghlxwxcb.cn/news/detail-781862.html
engine = create_engine('dialect+driver://username:password@host:port/database')
dialect: 數(shù)據(jù)庫類型
driver: 數(shù)據(jù)庫驅(qū)動(dòng)選擇
username: 數(shù)據(jù)庫用戶名
password: 用戶密碼
host: 服務(wù)器地址
port: 端口
database: 數(shù)據(jù)庫
if_exists='replace': 如果存在就替換
if_exists='append': 如果存在就追加
相反的,SQL導(dǎo)出到excel:文章來源地址http://www.zghlxwxcb.cn/news/detail-781862.html
from sqlalchemy import create_engine
import pandas as pd
# 創(chuàng)建數(shù)據(jù)庫連接
engine = create_engine('mysql+pymysql://root:passwd@localhost:port/testDB')
# 讀取mysql數(shù)據(jù)
db = pd.read_sql(sql='select * from testDB.t_book', con=engine)
# 導(dǎo)出數(shù)據(jù)到excel
db.to_excel('data.xlsx')
到了這里,關(guān)于Excel中的數(shù)據(jù)如何導(dǎo)入MySQL的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!