在实际的项目开发中,有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。
JDBC实现批处理有两种的两种方式:Statement和PreparedStatement。
一、使用Statement完成批处理
1. 使用Statement对象添加要批量执行SQL语句,如下:
Statement.addBatch(sql1);
Statement.addBatch(sql2);
Statement.addBatch(sql3);
2. 执行批处理SQL语句:Statement.executeBatch();
3.清除批处理命令: Statement.clearBatch();
1.1、使用Statement完成批处理范例
1. 用SQL脚本创建表
2.编写测试代码
package me.zl.demo;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import me.zl.utils.JdbcUtils;
public class JdbcBatchHandleByStatement {
//使用批处理实现JDBC批处理操作
public static void testJdbcBatchHandleByStatement() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql1 = "insert into testbatch(id,name) value(1,'Amy')";
String sql2 = "insert into testbatch(id,name) value(2,'Ben')";
String sql3 = "insert into testbatch(id,name) value(3,'Carry')";
String sql4 = "insert into testbatch(id,name) value(4,'David')";
String sql5 = "update testbatch set name='Chary' where id=3";
String sql6 = "insert into testbatch(id,name) value(5,'Fuck')";
String sql7 = "delete from testbatch where id=4";
st= conn.createStatement();
//添加要批量执行的SQL
st.addBatch(sql1);
st.addBatch(sql2);
st.addBatch(sql3);
st.addBatch(sql4);
st.addBatch(sql5);
st.addBatch(sql6);
st.addBatch(sql7);
//执行批处理命令
//st.executeBatch();
//清除批处理命令
st.clearBatch();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.release(conn, st, rs);
}
}
// public static void main(String[] args) {
// testJdbcBatchHandleByStatement();
// }
}
1.2 Statement.addBatch(sql)方式实现批处理的优缺点
优点:可以向数据库发送多条不同的SQL语句。
缺点:(1)SQL语句没有预编译。
(2)向数据库发送多条语句相同,但仅参数不同的SQL语句时,需写上很多条SQL语句。
二、使用PreparedStatement 完成批处理
2.1、使用PreparedStatement完成批处理范例
package me.zl.demo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import me.zl.utils.JdbcUtils;
//使用PreparedStatement实现JDBC批处理操作
public class JdbcBatchHandleByPreparedStatement {
public static void testJdbcBatchHandlePreparedStatement() {
long starttime = System.currentTimeMillis();
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "insert into testbatch(id,name) value(?,?)";
st = conn.prepareStatement(sql);
for(int i=1;i<1000;i++) {
st.setInt(1, i);
st.setString(2, "aa"+i);
st.addBatch();
if(i%100==0){
st.executeBatch();
//st.clearBatch();
}
}
st.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.release(conn, st, rs);
}
long endtime = System.currentTimeMillis();
System.out.println("程序所花时间:"+(endtime-starttime));
}
public static void main(String[] args) {
testJdbcBatchHandlePreparedStatement();
}
}
2.2 PreparedStatement.addBatch(sql)方式实现批处理的优缺点
优点:发送的是预编译后的SQL语句,执行效率高。缺点:只能在SQL语句相同,但参数不同的批处理中。因此,此形式的批处理经常用于在同一个表中批量插入数据,或批量更新表的数据。