批处理的概念
(1)当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率
(2)JDBC的批量处理语句包括下面三个方法:
addBatch(String):添加需要批量处理的SQL语句或是参数;
executeBatch():执行批量处理语句;
clearBatch():清空缓存的数据
代码演示
(1)没有使用批处理,插入50000条数据
package com.alex.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import org.junit.Test;
import com.alex.util.JDBCUtils;
public class TestConnection09 {
//没有使用批处理
//select count(*) from admin;
//truncate table admin;
//mysql 数据库检查 插入速度
//没有使用批处理
@SuppressWarnings("unused")
@Test
public void testNoBatch() throws Exception {
// 1.获取连接
Connection connection = JDBCUtils.getConnection();
// 2.访问数据库
PreparedStatement statement = connection.prepareStatement("insert into admin values(1,?,?)");
for (int i = 1; i <= 50000; i++) {
statement.setString(1, "小花" + i);
statement.setString(2, "0000");
statement.executeUpdate();
}
// 3.关闭
JDBCUtils.closeConnection(null, statement, connection);
}
}
执行了10秒中只插入了6719条数据,插入速度比较慢。
(2)使用批处理插入数据(数据库的连接地址要进行修改在后面加上"?rewriteBatchedStatements=true&useServerPrepStmts=false")
package com.alex.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import org.junit.Test;
import com.alex.util.JDBCUtils;
/**
* 批处理 情况:
* 一、多条sql语句的批量处理 适用于 sql语句各不一样,使用Statement命令对象执行
* 二、一条sql语句的批量传参
* 适用于sql语句一样,仅仅是参数不同,使用PreparedStatement命令对象指向
* 相关API
* addBatch:添加命令到批处理包
* executeBatch:提交批处理包
* clearBatch:清空批处理包
*
* 好处: 减少和数据库服务器连接的次数,减少执行的次数,提高效率
*/
public class TestConnection09 {
//使用批处理
@Test
public void test02() throws Exception{
// 1.获取连接
Connection connection = JDBCUtils.getConnection();
// 2.访问数据库
String sql="insert into admin values(1,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
for (int i = 1; i < 50000; i++) {
statement.setString(1, "小花" + i);
statement.setString(2, "8888");
// 批处理
statement.addBatch();// 将要执行的sql语句添加到批处理包(装篮子的操作)
if (i % 1000 == 0) {
statement.executeBatch();// 提交批处理的命令们(上楼运篮子的操作)
statement.clearBatch();// 清空批处理包(卸篮子的操作)
} else if (i > 49000) {
statement.executeBatch();// 提交批处理的命令们(上楼运篮子的操作)
statement.clearBatch();// 清空批处理包(卸篮子的操作)
}
}
// 3.关闭
JDBCUtils.closeConnection(null, statement, connection);
}
}
使用批处理,运行3秒就已经完成插入4999条数据,批处理的效率更高。