在jdbc中,批处理操作允许将多条sql语句一起执行,从而提高数据库操作的效率。以下是关于批处理的详细说明和示例代码:
在之前的JDBC操作中,我们通常是一条SQL语句执行一次。现在,通过批处理,我们可以将多条SQL语句组合在一起,一次性执行。
以下是批处理的基本使用示例:
package com.xdr630.jdbc.demo6;import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; import org.junit.Test; import com.xdr630.jdbc.utils.JDBCUtils;
/**
批处理操作示例
@author xdr */ public class JDBCDemo6 {
@Test /**
执行后的结果:
以下是使用PreparedStatement进行批量插入的示例:
@Test /**
批量插入记录
默认情况下MySQL批处理没有开启的,需要在url后面拼接一个参数即可。 */ public void demo2() { // 记录开始时间 long begin = System.currentTimeMillis(); Connection conn = null; PreparedStatement pstmt = null; try { // 获得连接 conn = JDBCUtils.getConnection(); // 编写SQL语句 String sql = "insert into user values (null, ?)"; // 预编译SQL pstmt = conn.prepareStatement(sql); for (int i = 1; i <= 10000; i++) { pstmt.setString(1, "name" + i); pstmt.addBatch(); if (i % 1000 == 0) { pstmt.executeBatch(); pstmt.clearBatch(); } } // 执行剩余的批处理 pstmt.executeBatch(); } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.release(pstmt, conn); } // 记录结束时间 long end = System.currentTimeMillis(); System.out.println("批量插入10000条记录耗时:" + (end - begin) + "毫秒"); }
为了启用MySQL的批处理,需要修改db.properties配置文件:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql:///test1?rewriteBatchedStatements=true username=root password=1234
执行完成后就会插入一万条记录: