JDBC中的executeBatch()方法用于批量執行SQL語句。下面是一個示例代碼演示如何使用executeBatch()方法:
```java
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();
}
}
}
}
```
在這個示例中,我們首先創建數據庫連接,然后創建一個預編譯的SQL語句。接著設置批量執行的參數,調用addBatch()方法將每一組參數添加到批處理中。最后調用executeBatch()方法執行批處理操作,并獲取執行結果。