萌新小白初试水——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效果:



浙公网安备 33010602011771号