在实际的项目开发中,有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。JDBC实现批处理有两种方式,如下:
使用Statement完成批处理
使用Statement完成批处理的步骤如下:
-
使用Statement对象添加要批量执行的SQL语句,如下:
Statement.addBatch(sql1); Statement.addBatch(sql2); Statement.addBatch(sql3);
-
执行批处理SQL语句。
Statement.executeBatch();
-
清除批处理命令。
Statement.clearBatch();
使用Statement完成批处理范例
首先,编写测试的SQL脚本创建表。
create table testbatch
(
id varchar(40) primary key,
name varchar(40)
);
然后,编写测试代码,如下所示:
package cn.liayun.demo;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import cn.liayun.utils.JdbcUtils;
public class Demo3 {
/*
create table testbatch
(
id varchar(40) primary key,
name varchar(40)
);
*/
//实现批处理的第一种方式
@Test
public void test1() throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql1 = "insert into testbatch(id,name) values('1','liayun')";//1.可以发送不同的sql语句 2.发送的sql语句没有预编译
String sql2 = "update testbatch set name='yemeimei' where id='1'";
st = conn.createStatement();// Statement内部维护了一个List集合,addBatch()方法加入的sql语句都加入到了该List集合内。
st.addBatch(sql1);
st.addBatch(sql2);
st.executeBatch();//返回int[]。例如[3,4]——即第一条sql语句执行影响数据库表几行,第二条sql语句执行影响数据库表几行,...
st.clearBatch();// 清除批处理命令
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
采用Statement.addBatch(sql)方式实现批处理的优缺点
使用PreparedStatement完成批处理
使用PreparedStatement完成批处理范例
package cn.liayun.demo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import cn.liayun.utils.JdbcUtils;
public class Demo3 {
/*
create table testbatch
(
id varchar(40) primary key,
name varchar(40)
);
*/
//实现批处理的第二种方式
@Test
public void test2() throws SQLException {
long starttime = System.currentTimeMillis();
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
/*
* 1. 适合做批量插入或者批量更新
* 2. 发送的sql语句都预编译过,性能会好一点。实际开发里,此种方式用到的多一点。
*/
String sql = "insert into testbatch(id,name) values(?,?)";
st = conn.prepareStatement(sql);
/*
for (int i = 1; i <= 10000000; i++) {
st.setString(1, i+"");
st.setString(2, "叶美美"+i);
st.addBatch();//批处理一千万条sql语句,会出现OutOfMemoryError:Java heap space——内存溢出错误
}
st.executeBatch();
*/
for (int i = 1; i <= 10000006; i++) {
st.setString(1, i + "");
st.setString(2, "yemeimei" + i);
st.addBatch();//把PreparedStatement对象内部封装的sql语句加到了PreparedStatement对象内部的List集合里面去了
//做大量批处理,易发生内存溢出错误。
if (i % 1000 == 0) {
st.executeBatch();
st.clearBatch();
}
}
st.executeBatch();// 剩下不到1000条sql语句也需要执行
} finally {
JdbcUtils.release(conn, st, rs);
}
long endtime = System.currentTimeMillis();
System.out.println("共花了:" + (endtime - starttime) / 1000 + "秒");// 向MySQL数据库批插入1000万条记录,大概需要3个多小时。而Oracle数据库测试大概需要380秒
}
}
采用PreparedStatement.addBatch()方式实现批处理的优缺点
关于JDBC批处理的内容就总结这么多。