jdbctemplate实现批量操作

需求:获取A库表字段与数据,插入到b库表中;
难点:无法确定插入字段数量及插入的字段类型。

//注入jdbctemplate
@resource
jdbctemplate jdbctemplate;
1.获取A库表字段数量:
	Statement statement = jdbcTemplate.getDataSource().getConnection().createStatement();
	//查A库表
	ResultSet rs = statement.executeQuery(sql);
	  List<String> columns = new ArrayList<>();

        ResultSetMetaData meta = rs.getMetaData();
        int cnt = meta.getColumnCount();
        for (int i = 0; i < cnt; i++) {
            columns.add(meta.getColumnTypeName(i+1));
        }
2.根据获取表字段数量,拼接values 后面的问号
String valParams = cols.stream().map(x -> "?").collect(Collectors.joining(",", "(", ")"));
//       拼接插入字段名,tableColumns字段名称,
String collect1 = tableColumns.stream().collect(Collectors.joining(",", "(", ")"));
String insertSql = "insert into " + table +" "+ collect1 + "values " + valParams;

3.实现批量操作
// dataList 需要插入的的数据
        List<String> finalRawList = dataList;
        jdbcTemplate.batchUpdate(insertSql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
            //第几批,批量插入
                int temp = i * cols.size();
                //一批插入多少个字段,遍历其类型,根据下标插入对应类型的值
                for (int j = 0; j < cols.size(); j++) {
                    int index = j + 1;
                    int param = j+temp;

                    String columnTypeName = cols.get(j);
//                  区分字段类型 设值
                    if (columnTypeName.contains("INT")) {
                        preparedStatement.setInt(index, Integer.parseInt(finalRawList.get(param)));
                    }
                    else if (columnTypeName.contains("DATE")){
                        preparedStatement.setDate(index, DateUtil.parse(finalRawList.get(param),"yyyy-MM-dd HH:mm:ss","yyyy/MM/dd HH:mm:ss").toSqlDate());
                    }
                    else if (columnTypeName.contains("VARCHAR")){
                        preparedStatement.setString(index, finalRawList.get(param));
                    }
                    else if (columnTypeName.contains("TIME")){
                        preparedStatement.setTimestamp(index, DateUtil.parse(finalRawList.get(param)).toTimestamp());
                    }
                }

            }

            @Override
            public int getBatchSize() {
            //遍历上边方法次数
                return finalRawList.size() / cols.size();

            }

        });

缺点:需自己定义涵盖的类型,进行判断插入值。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值