批处理的 三个关键步骤:
1. 在数据库的url后添加参数: rewriteBatchedStatements=true
jdbc:mysql://localhost:3306/myself?rewriteBatchedStatements=true
2. 使用 .addBatch()方法将操作添加到批处理中
3. 使用.executeBatch()方法 执行批处理操作
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcBatchExample {
// 数据库连接信息
private static final String URL = "jdbc:mysql://localhost:3306/your_database";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// 1. 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. 建立数据库连接
connection = DriverManager.getConnection(URL, USER, PASSWORD);
// 3. 创建 PreparedStatement 对象
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
preparedStatement = connection.prepareStatement(sql);
// 4. 添加批处理操作
preparedStatement.setString(1, "Alice");
preparedStatement.setString(2, "alice@example.com");
preparedStatement.addBatch();
preparedStatement.setString(1, "Bob");
preparedStatement.setString(2, "bob@example.com");
preparedStatement.addBatch();
preparedStatement.setString(1, "Charlie");
preparedStatement.setString(2, "charlie@example.com");
preparedStatement.addBatch();
// 5. 执行批处理操作
int[] updateCounts = preparedStatement.executeBatch();
// 6. 输出结果
System.out.println("Batch update completed. Number of rows affected: " + updateCounts.length);
} catch (ClassNotFoundException e) {
System.err.println("Database driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL error occurred.");
e.printStackTrace();
} finally {
// 7. 关闭资源
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}