Java JDBC executeBatchで高速一括処理【サンプルコード付】
JDBCのexecuteBatch()メソッドは、複数のSQL文を一括実行するために使用されます。以下は、executeBatch()メソッドの使用方法を示すサンプルコードです。
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();
}
}
}
}
この例では、まずデータベースへの接続を作成し、次にプリペアドステートメントを作成します。その後、バッチ処理を実行するためのパラメータを設定し、addBatch()メソッドを呼び出して各パラメータセットをバッチ処理に追加します。最後にexecuteBatch()メソッドを呼び出してバッチ処理を実行し、実行結果を取得します。