零、批处理的意义
在实际的项目开发中,有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。
JDBC实现批处理有两种方式:statement和preparedstatement。
例1
数据库t_stu表:
CREATE TABLE `t_stu` (
`sid` int(11) NOT NULL AUTO_INCREMENT,
`sname` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`gender` varchar(10) DEFAULT NULL,
PRIMARY KEY (`sid`)
)
Demo5.java:
package waf.yty.demo5;
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 waf.yty.utils.JdbcUtils;
/**
* 批处理
* @author yangtengyu
*
*/
public class Demo5 {
/**
* @throws SQLException
*
*/
@Test
public void fun5() throws SQLException {
ResultSet rs = null;
Connection con = JdbcUtils.getConnection();
String sql = "insert into t_stu values(?,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql);
for (int i = 0; i < 666; i++) {
pstmt.setInt(1, i+1);
pstmt.setString(2, "stu_" + i);
pstmt.setInt(3, i+16);
pstmt.setString(4, i%2==0?"男":"女");
pstmt.addBatch();
}
long start = System.currentTimeMillis();
pstmt.executeBatch();
long end = System.currentTimeMillis();
JdbcUtils.release(con, pstmt, rs);
System.out.println(end - start);
}
@Test
public void testJdbcBatchHandleByStatement() throws SQLException {
ResultSet rs = null;
Connection con = JdbcUtils.getConnection();
String sql1 = "insert into testbatch(name) values('aaa')";
String sql2 = "insert into testbatch(name) values('bbb')";
String sql3 = "insert into testbatch(name) values('CCC')";
String sql4 = "insert into testbatch(name) values('DDD')";
String sql5 = "update testbatch set name='wafyty' where id=1";
String sql6 = "insert into testbatch(name) values('FFF')";
String sql7 = "delete from testbatch where id=2";
String sql8 = "update testbatch set name = 'WAFYTY' where name = 'SMSBXKJ';";
Statement stmt = con.createStatement();
stmt.addBatch(sql1);
stmt.addBatch(sql2);
stmt.addBatch(sql3);
stmt.addBatch(sql4);
stmt.addBatch(sql5);
stmt.addBatch(sql6);
stmt.addBatch(sql7);
stmt.addBatch(sql8);
int[] batches = stmt.executeBatch();
stmt.clearBatch();
JdbcUtils.release(con, stmt, rs);
for (int i : batches) {
System.out.println(i);
}
System.out.println("笑哈哈");
for (int i = 0; i < batches.length; i++) {
int j = batches[i];
System.out.println(j);
}
}
}
一、statement和preparedstatement批处理的优缺点
1.1、采用Statement.addBatch(sql)方式实现批处理的优缺点
- 优点:可以向数据库发送多条不同的SQL语句。
- 缺点:SQL语句没有预编译。
当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句。例如:
1 Insert into user(name,password) values('aa','111');
2 Insert into user(name,password) values('bb','222');
3 Insert into user(name,password) values('cc','333');
1.2、采用PreparedStatement.addBatch()方式实现批处理的优缺点
- 优点:发送的是预编译后的SQL语句,执行效率高。
- 缺点:只能应用在SQL语句相同,但参数不同的批处理中。因此此种形式的批处理经常用于在同一个表中批量插入数据,或批量更新表的数据。