[JDBC]批处理

一.code

复制代码
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class TestBatch {
    @Test
    public void test1()throws Exception{
        //没有用批处理的功能
        long start = System.currentTimeMillis();

        //建立连接
        String url = "jdbc:mysql://localhost:3306/jdbctest";
        String user = "root";
        String pwd = "123456";
        Connection connection = DriverManager.getConnection(url, user, pwd);

        //编写sql
        String sql = "insert into t_department values(null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for(int i=1; i<=2000; i++){
            preparedStatement.setObject(1, "模拟部门名称" + i );
            preparedStatement.setObject(2, "模拟部门简介" + i );
            preparedStatement.executeUpdate();
            //执行2000遍
        }
        preparedStatement.close();
        connection.close();

        long end = System.currentTimeMillis();
        System.out.println("耗时:" +(end-start));
        //耗时:6554
    }

    @Test
    public void test2()throws Exception{
        //使用批处理功能
        long start = System.currentTimeMillis();

/*        MySQL服务器端,默认批处理功能没有开启。需要通过参数告知mysql服务器,开启批处理功能。
        在url后面再加一个参数 rewriteBatchedStatements=true*/
        //建立连接
        String url = "jdbc:mysql://localhost:3306/jdbctest";
        String pwd = "123456";
        String user = "root";
        Connection connection = DriverManager.getConnection(url, user, pwd);

        //编写sql
        String sql = "insert into t_department values(null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for(int i=2001; i<=4000; i++){
            preparedStatement.setObject(1, "模拟部门名称a" + i );
            preparedStatement.setObject(2, "模拟部门简介b" + i );
            preparedStatement.addBatch();//先攒着
        }
        preparedStatement.executeBatch();//执行批处理功能

        preparedStatement.close();
        connection.close();

        long end = System.currentTimeMillis();
        System.out.println("耗时:" +(end-start));//耗时:729
    }
}
相关推荐
karry_k19 分钟前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k26 分钟前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
SamDeepThinking4 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
她的男孩7 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
荣码9 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
plainGeekDev10 小时前
Gson → kotlinx.serialization
android·java·kotlin
小bo波19 小时前
Java Swing 图形用户界面实验 —— 从算术练习到游戏开发的完整实践
java·课程设计·gui·游戏开发·扫雷·swing
咖啡八杯20 小时前
GoF设计模式——备忘录模式
java·后端·spring·设计模式