[JDBC]批处理

📅 发布时间:2026/7/9 11:38:22 👁️ 浏览次数:
[JDBC]批处理
一.codeimport 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 i1; i2000; 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后面再加一个参数 rewriteBatchedStatementstrue*/ //建立连接 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 i2001; i4000; 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}}