使用PreparedStatement进行批量插入

有一个文本文件,按照某些字符进行分割,需要导入数据库。下面给出比较通用的方法。

    public static void batchInsert(Connection connection, File file, String splitStr, int batchSize) throws Exception {
        long start = System.currentTimeMillis();
        String fileName = file.getName();
        BufferedReader reader = new BufferedReader(new FileReader(file));


        //保存文件名和表字段个数的关系
        Integer numOfQuote = map.get(fileName);
        String[] quotes = new String[numOfQuote];
        Arrays.fill(quotes,"?");
        String sql = "INSERT INTO `" + fileName.replace(".csv", "") + "` VALUES (" + Joiner.on(",").join(quotes) + ")";
        System.out.println("sql:" + sql);

        connection.setAutoCommit(false);
        PreparedStatement cmd = connection.prepareStatement(sql);

        int count = 0;
        try {
            String line = null;
            while (StrUtil.isNotEmpty(line = reader.readLine())) {
                //split的第二个参数设为-1,才能处理分割之后很多空串的情况,否则可能字段少了
                //https://blog.csdn.net/wx1528159409/article/details/92796234
                String[] split = line.split(splitStr, -1);
                //不匹配的抛弃
                if (split.length != numOfQuote) {
                    continue;
                }
                count++;
                for (int j = 0; j < numOfQuote; j++) {
                    cmd.setString(j + 1, split[j]);
                }
                cmd.addBatch();

                if (count % batchSize == 0) {
                    cmd.executeBatch();
                    cmd.clearBatch();
                }
            }

            cmd.executeBatch();
            cmd.clearBatch();
            connection.commit();
        } finally {
            IoUtil.close(cmd);
            IoUtil.close(reader);
        }

        long end = System.currentTimeMillis();
        System.out.println("批量插入需要时间:" + (end - start));
    }

JDBC连接URL字符串中需要新增一个参数:rewriteBatchedStatements=true。并保证5.1.13以上版本的驱动,才能实现高性能的批量插入。MySQL JDBC驱动在默认情况下会无视executeBatch()语句,把我们期望批量执行的一组sql语句拆散,一条一条地发给MySQL数据库,批量插入实际上是单条插入,直接造成较低的性能。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值