首页 > 数据库 >Excel 20w数据解析成可插入SQL脚本

Excel 20w数据解析成可插入SQL脚本

时间:2023-01-11 00:11:40浏览次数:39  
标签:goods String 20w SQL Excel static new import null

背景:上游系统有15万+生产商品数据要导入到我们系统(只同步一次),这个数据需要各个服务owner修改完价格之后一一确认之后才能导入,既然是多个人经手改,模板就可能会变动,使用excel导入的方式同步到系统 存在以下问题
1.模板可能改动,导入字段映射需要跟着改变
2.导入分批插入事物无法保证
3.只使用一次的不应该做为功能,管理员可能误操作导致数据问题
权衡之后决定使用通过解析Excel将数据转换之后在生成SQL插入语句,这样修改业务excel变动了,直接在本地调整映射关系,更灵活

使用方式基于阿里开源框架EasyExcel导入导出性能及优,使用反射生成SQL语句

1.引入依赖包
 
   <dependencies>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.22</version>
        </dependency>
 

2.解析Excel分批生成SQL

package com.lhl.http.com.lhl.sql;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class GenerateSql {

public static void main(String[] args) throws IOException {
String excelPath = "D:\\商品信息.xlsx";
String sqlPth = "d:\\t_goods.sql";
parseExcelConvertSql(excelPath, sqlPth);
}

public static void parseExcelConvertSql(String excelFilePath, String sqlFilePath) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(sqlFilePath));
// excel分页解析,默认每批次100条
EasyExcel.read(excelFilePath, new PageReadListener<Map<Integer, String>>(dataList -> {
dataList.forEach(data -> {
Goods goods = convertMap(data);
String sql = getInsertSql("t_goods", Goods.class, goods);
try {
bw.write(sql + ";\n");
bw.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
})).sheet().doRead();
}

/**
* 基于对象生成插入sql
*/
public static <T> String getInsertSql(String tableName, Class<T> clazz, T t) {
Field[] fields = ReflectUtil.getFields(clazz);
StringBuffer topHalf = new StringBuffer("insert into " + tableName + "(");
StringBuffer afterAalf = new StringBuffer("values(");
for (Field field : fields) {
topHalf.append(field.getName() + ",");
if (ReflectUtil.getFieldValue(t, field.getName()) instanceof String) {
afterAalf.append("'" + ReflectUtil.getFieldValue(t, field.getName()) + "',");
} else {
afterAalf.append(ReflectUtil.getFieldValue(t, field.getName()) + ",");
}
}
topHalf = new StringBuffer(StrUtil.removeSuffix(topHalf.toString(), ","));
afterAalf = new StringBuffer(StrUtil.removeSuffix(afterAalf.toString(), ","));
topHalf.append(")");
afterAalf.append(")");
return topHalf + afterAalf.toString();
}

private static Goods convertMap(Map<Integer, String> data) {
Map map = new HashMap();
for (Integer key : indexColumnMap.keySet()) {
map.put(indexColumnMap.get(key), data.get(key));
}
map.put("id", getId());
Goods goods = new Goods();
return BeanUtil.fillBeanWithMap(map, goods, true, true);
}

/**
* 生成唯一id
* @return
*/
private static String getId() {
Snowflake snowflake1 = IdUtil.getSnowflake(1, 1);
return snowflake1.nextIdStr();
}

/**
* excel列和字段映射关系
*/
private static Map<Integer, String> indexColumnMap = new HashMap();

static {
int index = 0;
indexColumnMap.put(index++, "goodName");
indexColumnMap.put(index++, "price");
indexColumnMap.put(index++, "createBy");
indexColumnMap.put(index++, "createDate");
}

@Getter
@Setter
@NoArgsConstructor
public static class Goods {
private String id;
private String good_name;
private double price;
private String create_by;
private String create_date;
}
}

 

3.生成结果

insert into t_goods(id,good_name,price,create_by,create_date)values('1612839604908593152',null,5300.0,null,null);
insert into t_goods(id,good_name,price,create_by,create_date)values('1612839604916981760',null,5300.0,null,null);
insert into t_goods(id,good_name,price,create_by,create_date)values('1612839604916981761',null,5300.0,null,null);

标签:goods,String,20w,SQL,Excel,static,new,import,null
From: https://www.cnblogs.com/mike3504/p/17041845.html

相关文章

  • python操作mysql数据库,增删查改等需要执行后加commit()
    p1:关于commit方法第一感觉是这个方法只用来提交“数据”,比如插入数据、更新数据需要在execute()后面跟上一个commit();现在看来,commit()方法需要跟在增(insert)、删(delete)、......
  • MySQL UPDATE:修改数据-更新数据-在原有表基础上增加列--python
    使用UPDATE语句修改单个表,语法格式为:UPDATE<表名>SET字段1=值1[,字段2=值2…][WHERE子句][ORDERBY子句][LIMIT子句]语法说明如下:<表名>:用于指定要......
  • mysql
    mysqlMySQL上篇:基础篇】【第1子篇:数据库概述与MySQL安装篇】p01-p11学习建议:零基础同学必看,涉及理解和Windows系统下MySQL安装【第2子篇:SQL之SELECT使用篇】p12-p48......
  • sql语句之_(limit)
    select*fromt_addresswhereuid=#{uid}orderbymodified_timeDESClimit0,1--limit0,1的意思是---->从"t_address数据库"的第0条数据开始,......
  • RDS For MySQL 本地还原
    RDSFORMySQL下载至本地还原:参考:​​​https://help.aliyun.com/knowledge_detail/41817.html?spm=a2c4g.11186623.4.3.596e10721NSVa5​​完整实例:db_rds_backup.tar日......
  • SQL Server 2019 新增函数
     sys.dm_db_page_info某个数据页的头部信息USEmasterGOCREATEDATABASETest;GOUSETest;GOSELECT[object_id]asobjectid,name,type_desc,create_date,modify_dateIN......
  • SQL Server 2016 Always Encrypted(始终加密)
    AlwaysEncrypted功能旨在保护AzureSQLDatabase或SQLServer数据库中存储的敏感数据,如信用卡号或身份证号(例如美国社会安全号码)。始终加密允许客户端对客户端应用程......
  • 简易版NewSql数据库--单机版kv存储
    数据结构:哈希桶,每个桶内可以装8个数据,然后每一个桶20个相同的桶,在写入的时候,首先通过哈希找到对应的桶,然后在根据当前该哈希值已经有的数量,判断要找存到20个......
  • SparkSQL与Hive查询不一致问题
    问题Sparksql查询出的数据量与hive不一致,重启spark就没问题,查询结果一致。或者报错说读取的文件不存在,类似如下的错误FileReadException:Errorwhilereadingfilexxx.......
  • SQL优化案例9(广东某管理局项目)
    同事找我优化SQL,同一条SQL语句LIKE过滤条件不同,执行时间差别很多,废话不说安排一下。LIKE过滤条件执行快的SQL和执行计划:EXPLAINANALYZESELECTcase_id,cate_......