使用JDBC进行批处理
1.业务场景
当需要向数据库发送一批SQL语句执行时,应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。
默认情况下Mysql的批处理仍然是一条一条执行,需要在url后面添加rewriteBatchedStatements=true参数
2.第一种方式:Statement.addBatch(sql)
2.1 优点:可以向数据库发送多条不同的SQL语句。
2.2缺点:SQL语句没有预编译。
当向数据库发送多条语句相同,但仅参数不同的SQL语句时,
需重复写上很多条SQL语句。例如:
Insert into user(name,password) values(‘aa’,’111’);
Insert into user(name,password) values(‘bb’,’222’);
Insert into user(name,password) values(‘cc’,’333’);
Insert into user(name,password) values(‘dd’,’444’);
//Statement批处理
@Test
public void testInsertBatch() throws SQLException {
long startTime =System.currentTimeMillis();
// 这里这个batch想当是一个小推车,帮助我们更好的搬砖
for (int i = 0; i < 100000; i++) {
String username = "小金刚" + i;
//statement.addBatch
//优点:可以向数据库发送多条不同的SQL语句。
//缺点:
//SQL语句没有预编译。
//当向数据库发送多条语句相同,但仅参数不同的SQL语句时,
//需重复写上很多条SQL语句。
statement.addBatch("insert into user values (null,'"+username+"','cskaoyan','male')");
}
//executeBatch()方法:执行批处理命令
//clearBatch()方法:清除批处理命令
statement.executeBatch();
statement.close();
long endTime = System.currentTimeMillis();
System.out.println("statement批处理:" + (endTime -startTime));
//2454
}
3.第二种方式:PreparedStatement.addBatch()
3.1 优点:PreparedStatment批量操作时与数据库的通信次数远少于Statment。
3.2 缺点:只能应用在SQL语句相同,但参数不同的批处理中。
因此此种形式的批处理经常用于在同一个表中批量插入数据,或批量更新表的数据。
// prepareStatement 进行批处理
@Test
public void testPrepareStatementBatch() throws SQLException {
//con
PreparedStatement preparedStatement = connection.prepareStatement("insert into user values (null,?,?,?)");
long startTime = System.currentTimeMillis();
// 批量放入
for (int i = 0; i <10000; i++) {
String username = "小蝴蝶" + i;
preparedStatement.setString(1,username);
preparedStatement.setString(2,"cskaoyan111");
preparedStatement.setString(3,"male");
preparedStatement.addBatch();
}
// 批处理执行
int[] ints = preparedStatement.executeBatch();
long endTime = System.currentTimeMillis();
System.out.println("prepareStatement批处理:" + (endTime -startTime));
// 2019
}
4.详细实现
4.1 结构
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gy</groupId>
<artifactId>JDBC-batch</artifactId>
<version>28.0-SNAPSHOT</version>
<dependencies>
<!-- 导入JDBC的Mysql实现,这个也就是JDBC的数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
JDBCUtils.java
public class JDBCUtils {
private static String url;
private static String username;
private static String password;
private static String driverName;
static {
try {
// 加载配置文件
Properties properties = new Properties();
// 通过类加载器去获取
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("jdbc.properties");
properties.load(inputStream);
// 取值 赋值
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
driverName = properties.getProperty("driverName");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection(){
Connection connection = null;
// 1. 注册驱动
try {
Class.forName(driverName); // = "new Driver()"
// DriverManager.registerDriver(new Driver());
// 2. 获取连接
connection = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
// 释放资源
public static void releaseSources(Connection connection, Statement statement, ResultSet resultSet){
// 释放资源
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
jdbc.properties
url=jdbc:mysql://localhost:3306/testdb1?useSSL=false&characterEncoding=utf-8
username=root
password=123456
driverName=com.mysql.jdbc.Driver
JDBCTestBatch.java
public class JDBCTestBatch {
static Connection connection = null;
static Statement statement = null;
@BeforeClass
public static void testBefore() throws SQLException {
connection = JDBCUtils.getConnection();
statement = connection.createStatement();
}
@AfterClass
public static void destory() {
JDBCUtils.releaseSources(connection, statement, null);
}
//Statement批处理
@Test
public void testInsertBatch() throws SQLException {
long startTime = System.currentTimeMillis();
// 这里这个batch想当是一个小推车,帮助我们更好的搬砖
for (int i = 0; i < 999; i++) {
String username = "小金刚" + i;
//statement.addBatch
//优点:可以向数据库发送多条不同的SQL语句。
//缺点:SQL语句没有预编译。当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句。
statement.addBatch("insert into user values (null,'" + username + "','cskaoyan','male')");
}
//executeBatch()方法:执行批处理命令
//clearBatch()方法:清除批处理命令
statement.executeBatch();
statement.close();
long endTime = System.currentTimeMillis();
System.out.println("statement批处理:" + (endTime - startTime));
}
// prepareStatement 进行批处理
@Test
public void testPrepareStatementBatch() throws SQLException {
//con
PreparedStatement preparedStatement = connection.prepareStatement("insert into user values (null,?,?,?)");
long startTime = System.currentTimeMillis();
// 批量放入
for (int i = 0; i < 999; i++) {
String username = "小蝴蝶" + i;
preparedStatement.setString(1, username);
preparedStatement.setString(2, "cskaoyan111");
preparedStatement.setString(3, "male");
preparedStatement.addBatch();
}
// 批处理执行
int[] ints = preparedStatement.executeBatch();
long endTime = System.currentTimeMillis();
System.out.println("prepareStatement批处理:" + (endTime - startTime));
}
}