package com.demo.jdbc;
import com.demo.utils.JdbcUtils2;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
/**
* 批处理执行 sql 语句
* addBatch(String sql) 添加批处理
* clearBatch() 清空批处理
* executeBatch() 执行批处理
*/
public class JdbcDemo5 {
@Test
public void test1(){
Connection conn = null;
PreparedStatement pstmt = null;
// 模拟批量数据
List<User> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
User user = new User("Jack" + i, "123" + i);
list.add(user);
}
try{
// 1、获取数据库连接对象
conn = JdbcUtils2.getConnection();
// 2、准备预编译 sql 语句
String sql = "insert into users(username, password) values(?, ?)";
// 3、预编译 sql 语句,创建 pstmt 对象
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < list.size(); i++) {
User user = list.get(i);
// 4、设置参数
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
// 5、添加批处理
pstmt.addBatch();
// 6、每 5条 执行一次批处理
if (i % 5 == 0){
pstmt.executeBatch(); // 执行批处理
pstmt.clearBatch(); // 清空批处理
System.out.println("执行了批处理!i:" + i);
}
}
pstmt.executeBatch(); // 执行批处理
pstmt.clearBatch(); // 清空批处理
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils2.close(conn, pstmt, null);
}
}
}
其中 JdbcUtils2.java 工具类为:https://blog.csdn.net/qq_29331365/article/details/95166514