[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
    }
}
相关推荐
Seven9713 小时前
两小时入门Sentinel
java
tongluowan00713 小时前
Java中atomic底层原理 - ABA 问题与解决方案
java·juc·atomic
无关868814 小时前
Spring Boot 项目标准化部署打包实战
java·spring boot·后端
jay神14 小时前
基于微信小程序课外创新实践学分认定系统
java·spring boot·小程序·vue·毕业设计
Gauss松鼠会14 小时前
GaussDB(DWS) GUC参数修改、查看
java·数据库·sql·数据库开发·gaussdb
AIFQuant14 小时前
Java 对接全球股票实时报价:高可用架构与异常处理
java·开发语言·websocket·金融·架构·股票api
未若君雅裁14 小时前
Spring Bean 作用域、线程安全与生命周期
java·安全·spring
奋斗的小乌龟14 小时前
langchain4j笔记-智能体系统01
java·笔记
wh_xia_jun14 小时前
用pom 的test 配置 与 jacoco
java·ide·intellij-idea
阿丰资源14 小时前
基于Spring Boot的酒店客房管理系统
java·spring boot·后端