萌新小白初試水——excel表格資料匯入資料庫MySQL
一、需求大致說明:
1、匯入excel的內容到資料庫中,
2、其中details_json要求符合json字串格式。
3、資料庫採用MySQL
需求具體解讀:
1、excel資料樣式:
2、入庫結果:
3、規則輔助理解:
二、具體步驟:
(一)、開啟MySQL資料庫,開啟查詢--->新建查詢--->輸入建表語句
語句複製:
create table middle_map_point_info
(
id int auto_increment comment '主鍵
primary key,
name varchar(127) null comment '節點名稱',
longitude decimal(16, 8) null comment '經度',
latitude decimal(16, 8) null comment '緯度',
details_json text null comment '節點詳情Json',
update_time datetime null comment '更新時間',
type varchar(127) null comment '型別
parent_type varchar(127) null comment '父級型別'
)
comment '中間地圖點位資訊表';
(二) 開啟python的編譯工具(這裡用pycharm)建立專案,敲程式碼:
#匯入所需要用到的庫
import xlrd
import pymysql
import time #這個庫是寫者這個檔案需要輸入當下時間用的,不是主題所必須的庫
#開啟資料所在工作薄,以及選擇存有資料的工作表
book = xlrd.open_workbook("excel_1.xls")
sheet = book.sheet_by_name("Sheet1")
#建立MySQL連線
con = pymysql.connect(
host = 'localhost', #主機名或ip地址
user = 'root', #使用者名稱
passwd = 'Qning445', #密碼
db = 'lianxi_1', #資料庫名字
port = 3306, #埠
charset = 'utf8' #位元組編碼
)
#獲得遊標
cur = con.cursor()
#建立插入SQL語句
query1 = 'insert into middle_map_point_info (name,Longitude,Latitude,details_json,update_time,type,parent_type) values (%s,%s,%s,%s,%s,%s,%s)'
#建立一個for迴圈迭代讀取xlsx檔案每行資料,從第二行開始跳過標題行
for r in range(1,sheet.nrows):
name = sheet.cell(r,0).value #易澇點名稱
management = sheet.cell(r,2).value #管理單位
Longitude = sheet.cell(r,3).value #經度
Latitude = sheet.cell(r,4).value #緯度
datails_json = "({\"易澇點名稱\":"+name+",\"管理單位\":"+management+"})" #json欄位
update_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) #當前更新時間
type = "風險隱患" #固定欄位
parent_type = "易澇路段" #固定欄位
values = (name,Longitude,Latitude,datails_json,update_time,type,parent_type)
#執行sql語句
cur.execute(query1,values)
#關閉連線、關閉資料庫
cur.close()
con.commit()
con.close()
#獲取excel資料傳入資料庫的資料行列數(順便可以直接讓我判斷程式碼是否成功咧。)
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print("匯入" + columns + "列" + rows + "行資料到MySQL資料庫!")
三、結果:
PyCharm執行結果
MySQL效果: