[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
    }
}
相关推荐
文丑颜不良啊1 小时前
LeetCode2761~2780题目解析
java·leetcode
IT枫斗者枫哥2 小时前
子线程断言失败,JUnit 为什么还显示通过?
java·后端
考虑考虑4 小时前
JDK27中的Set.ofLazy
java·后端·java ee
文丑颜不良啊4 小时前
LeetCode2841~2860题目解析
java·leetcode
小南家的青蛙4 小时前
Tomcat与Jetty深度对比
java·tomcat·jetty
乌暮6 小时前
Spring AOP 与 Spring 事务:用大白话彻底理解原理与实践
java·数据库·spring boot·后端·sql·学习·spring
YDS8296 小时前
Small Spring IOC篇:容器事件及其监听器
java·spring
金銀銅鐵6 小时前
带您看懂字节码指令(三):一行加法里有什么
java·jvm
文丑颜不良啊6 小时前
LeetCode2921~2940题目解析
java·leetcode
北漂人Java7 小时前
基于 Spring AI Alibaba WorkFlow 构建 Java 生产级 AI Agent
java·人工智能·spring