Batch processing in JDBC refers to the execution of a group of similar database operations as a single unit, resulting in improved performance and reduced overhead. Instead of executing each database operation individually, batch processing allows you to send multiple operations to the database server in a single round-trip, minimizing network latency.
Here's an example code snippet that demonstrates batch processing in JDBC:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class BatchProcessingExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "your-username";
String password = "your-password";
try (Connection connection = DriverManager.getConnection(url, username, password)) {
connection.setAutoCommit(false); // Disable auto-commit
String insertQuery = "INSERT INTO employees (id, name, age) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(insertQuery);
// Add multiple operations to the batch
statement.setInt(1, 1);
statement.setString(2, "John");
statement.setInt(3, 30);
statement.addBatch();
statement.setInt(1, 2);
statement.setString(2, "Jane");
statement.setInt(3, 35);
statement.addBatch();
statement.setInt(1, 3);
statement.setString(2, "Mike");
statement.setInt(3, 40);
statement.addBatch();
// Execute the batch
int[] result = statement.executeBatch();
connection.commit(); // Commit the transaction
connection.setAutoCommit(true); // Enable auto-commit (if desired)
System.out.println("Batch processing completed successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In this example, we establish a connection to a MySQL database using JDBC. We disable auto-commit mode using setAutoCommit(false) to allow manual transaction control. We create a PreparedStatement using the INSERT query and add multiple sets of parameter values using setX methods (e.g., setInt, setString). We add each set of parameters to the batch using addBatch(). Finally, we execute the batch using executeBatch(), which returns an array of update counts for each operation in the batch.
After executing the batch, we commit the transaction using commit(), and then enable auto-commit mode again using setAutoCommit(true) (if desired). The batch processing completes, and a success message is displayed.
Note: Make sure to replace your-username and your-password with your actual database credentials, and mydatabase with the name of your database. Also, ensure that you have the appropriate JDBC driver for your database configured in your project.