jdbc批量插入

1. 开启JDBC

rewriteBatchedStatements=true

2. 准备数据

PreparedStatement preparedStatement = connection.prepareStatement(InsertSql);

3. 插入数据并添加到批次

preparedStatement.setObject(columnIndex, resultSet.getObject(columnIndex));
preparedStatement.addBatch();

4. 批量提交并清空批次

if (resultSet.getRow() % 500 == 0) {
    log.info("当前行数:" + resultSet.getRow());
    preparedStatement.executeBatch();
    preparedStatement.clearBatch();
}

if (resultSet.isLast()) {
    log.info("最后一行:" + resultSet.getRow());
    preparedStatement.executeBatch();
    preparedStatement.clearBatch();
}

5. 注意点

1. SQL最后不能带有分号(;),否则会报错【BatchUpdateException】
2. 批量提交数量不能过高,可能会导致提交的SQL过长,导致执行报错。

demo

    /**
     * 使用PreparedStatement ps;的
     *      ps.addBatch();      将sql语句打包到一个容器中
     *      ps.executeBatch();  将容器中的sql语句提交
     *      ps.clearBatch();    清空容器,为下一次打包做准备
     * 这三个方法实现sql语句打包,累计到一定数量一次提交
     */
    @Test
    public void bulkSubmissionTest2() {
        long start = System.currentTimeMillis();
        Connection conn = jdbcUtils.getConnection();//获取数据库连接
        String sql = "insert into a(id, name) VALUES (?,null)";
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 1; i <= 1000000; i++) {
                ps.setObject(1, i);
                ps.addBatch();//将sql语句打包到一个容器中
                if (i % 500 == 0) {
                    ps.executeBatch();//将容器中的sql语句提交
                    ps.clearBatch();//清空容器,为下一次打包做准备
                }
            }
            //为防止有sql语句漏提交【如i结束时%500!=0的情况】,需再次提交sql语句
            ps.executeBatch();//将容器中的sql语句提交
            ps.clearBatch();//清空容器
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            jdbcUtils.close(conn, ps, null);
        }
        System.out.println("百万条数据插入用时:" + (System.currentTimeMillis() - start)+"【单位:毫秒】");
    }

posted @ 2023-11-14 18:48  chenzechao  阅读(35)  评论(0编辑  收藏  举报