actual combat 28 —— jdbcTemplate.batchUpdate实际应用例子,这个操作是不是有点危险。。。

    @PostMapping("/sql/execute")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(@RequestParam("sqlFile") MultipartFile sqlFile,
                                 @RequestParam("account") String account,
                                 @RequestParam("password") String password,
                                 @RequestParam("anhao") String anhao) throws Exception {
        if (!Objects.equals(account, "111")) {
            throw new ServiceException("账号不正确");
        }
        if (!Objects.equals(password, "2222")) {
            throw new ServiceException("密码不正确");
        }
        if (!Objects.equals(anhao, "3333")) {
            throw new ServiceException("执行失败");
        }

        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(sqlFile.getInputStream()))) {
            String line;
            while (StringUtils.isNotEmpty(line = reader.readLine())) {
                String subLine = line.substring(0, line.length() -1);
                lines.add(subLine);
            }
        }

        String[] sqlStatements = lines.toArray(new String[0]);
        int[] resultArray = jdbcTemplate.batchUpdate(sqlStatements);
        int[] evenIndices = IntStream.range(0, resultArray.length)
                .filter(index -> resultArray[index] != 1)
                .toArray();

        if(evenIndices.length != 0) {
            throw new ServiceException(Arrays.toString(evenIndices));
        }
        return AjaxResult.success();
    }

需要注意的是,sql文件中若有多个insert或update、delete的操作,无需用;隔开

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值