【JDBC】批量插入数据优化

一、使用普通的方式插入10000条数据

@Test
public void testInsert() throws Exception {
    //1.注册驱动
    Class.forName("com.mysql.cj.jdbc.Driver");

    //2.获取连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/itcast?user=root&password=123456");

    //3.编写sql语句
    String sql = "insert into employee(name, salary, departmentId) values(?, ?, ?);";

    //4.创建statement
    PreparedStatement preparedStatement = connection.prepareStatement(sql);

    //5.占位符赋值
    long start = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++) {
        preparedStatement.setObject(1, "dd" + i);
        preparedStatement.setObject(2, 5);
        preparedStatement.setObject(3, 2);

        //6.发送sql语句,并且获取结果
        preparedStatement.executeUpdate();
    }

    long end = System.currentTimeMillis();

    System.out.println("执行100000次数据插入消耗的时间" + (end - start) + "ms");
    //8.关闭资源
    connection.close();
    preparedStatement.close();
}

可以测出,一共用了14000多ms


二、使用批量插入的方式插入100000条数据

我们在执行insert语句的时候,其实可以一次携带多个值

insert into employee(name, salary, departmentId) values(?, ?, ?), (),()

代码示例

@Test
public void testBatchInsert() throws Exception {
    // 1.注册驱动
    Class.forName("com.mysql.cj.jdbc.Driver");

    // 2.获取连接
    Connection connection = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/itcast?rewriteBatchedStatements=true", "root", "123456");

    // 3.编写sql语句
    String sql = "insert into employee(name, salary, departmentId) values(?, ?, ?)";

    // 4.创建statement
    PreparedStatement preparedStatement = connection.prepareStatement(sql);

    //5.占位符赋值
    long start = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++) {
        preparedStatement.setObject(1, "dd" + i);
        preparedStatement.setObject(2, 5);
        preparedStatement.setObject(3, 2);

        // preparedStatement.executeUpdate();
        preparedStatement.addBatch();// 不执行,追加到values后面!
    }
    preparedStatement.executeBatch();// 执行批量操作!
    // 这里可能会有另外的一个方法:statement.executeLargeBatch(); //这个方法是假的,jdbc里面没有任何操作!!

    long end = System.currentTimeMillis();

    System.out.println("执行100000次数据插入消耗的时间" + (end - start) + "ms");
    //8.关闭资源
    connection.close();
    preparedStatement.close();
}

结果为:254ms,可以发现明显优化了很多


三、总结

1.url路径后面添加 ?rewriteBatchedStatements=true 允许批量插入
2.insert into 必须写values, 语句末尾 不能 添加 “;” 结束,因为它是采用追加的方式接上SQL语句的
3.不是执行语句每条,是批量添加 addBatch();
4.遍历添加完毕以后,统一批量执行 executeBatch()

如下图可以看见 executeLargeBatch方法 中并没有执行任何操作,因此它其实是一个假方法

image-20240725185958613

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值