Java JDBC executeBatch: Batch Execution Guide
The executeBatch() method in JDBC is used to execute SQL statements in batches. Below is an example code demonstrating how to use the executeBatch() method.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class BatchExecutionExample {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// 创建数据库连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
// 创建预编译的SQL语句
String sql = "INSERT INTO my_table (column1, column2) VALUES (?, ?)";
preparedStatement = connection.prepareStatement(sql);
// 设置批量执行的参数
preparedStatement.setString(1, "value1");
preparedStatement.setString(2, "value2");
preparedStatement.addBatch();
preparedStatement.setString(1, "value3");
preparedStatement.setString(2, "value4");
preparedStatement.addBatch();
// 执行批量操作
int[] result = preparedStatement.executeBatch();
// 输出批量操作结果
for (int i : result) {
System.out.println("Number of rows affected: " + i);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
In this example, we first establish a database connection and then create a precompiled SQL statement. Next, we set the parameters for batch execution, adding each group of parameters to the batch with the addBatch() method. Finally, we execute the batch operation with the executeBatch() method and retrieve the results of the execution.