JavaWeb学习总结(十一)--JDBC之批处理

时间:2023-03-09 09:03:41
JavaWeb学习总结(十一)--JDBC之批处理

一、批处理的介绍

在实际的项目开发中,有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。批处理只针对更新(增、删、改)语句,批处理没有查询什么事儿!

JDBC实现批处理有两种方式:statement和preparedstatement

可以多次调用Statement类的addBatch(String sql)方法,把需要执行的所有SQL语句添加到一个“批”中,然后调用Statement类的executeBatch()方法来执行当前“批”中的语句。

  • void addBatch(String sql):添加一条语句到“批”中;
  • int[] executeBatch():执行“批”中所有语句。返回值表示每条语句所影响的行数据;
  • void clearBatch():清空“批”中的所有语句。

注意:mysql是默认是没有开启批处理的,需要加参数:jdbc:mysql://localhost:3306/testdb?rewriteBatchedStatements=true

二、Statement批处理

1. 创建测试表

create table testbatch(
id int primary key,
name varchar(20)
)

2. 执行代码

package cn.zy.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement; import org.junit.Test; import cn.zy.utils.JdbcUtils; public class BatchHandle {
/*
* 使用statement实现批处理
*/
@Test
public void BatchByStatement(){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql1 = "insert into testbatch(id,name) values(1,'aaa')";
String sql2 = "insert into testbatch(id,name) values(2,'bbb')";
String sql3 = "insert into testbatch(id,name) values(3,'CCC')";
st = conn.createStatement();
//添加要批量执行的SQL
st.addBatch(sql1);
st.addBatch(sql2);
st.addBatch(sql3);
//执行批处理
st.executeBatch();
//清除批处理命令
st.clearBatch();
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtils.release(conn, st, rs);
}
} }

采用Statement.addBatch(sql)方式实现批处理的优缺点

  采用Statement.addBatch(sql)方式实现批处理:
    优点:可以向数据库发送多条不同的SQL语句。
    缺点:SQL语句没有预编译。
    当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句。

三、采用PreparedStatement实现批处理

代码如下:

package cn.zy.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import cn.zy.utils.JdbcUtils; public class BatchHandle { /*
* 使用preparedstatement实现批处理
*/
@Test
public void BatchByPreparedStatement(){
long starttime = System.currentTimeMillis();
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "insert into testbatch(id,name) values(?,?)";
st = conn.prepareStatement(sql);
for(int i=1;i<100000;i++){
st.setInt(1, i);
st.setString(2, "dog"+i);
st.addBatch();
if(i%1000==0){
st.executeBatch();
st.clearBatch();
}
}
st.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcUtils.release(conn, st, rs);
}
long endtime = System.currentTimeMillis();
System.out.println("程序花费时间:" + (endtime-starttime)/1000 + "秒!!");
}
}

可以看见插入百万条数据所需要的时间这里是:

JavaWeb学习总结(十一)--JDBC之批处理

采用PreparedStatement.addBatch()方式实现批处理的优缺点

  采用PreparedStatement.addBatch()实现批处理
    优点:发送的是预编译后的SQL语句,执行效率高。
    缺点:只能应用在SQL语句相同,但参数不同的批处理中。因此此种形式的批处理经常用于在同一个表中批量插入数据,或批量更新表的数据。