To batch insert data with JDBC, you typically use the addBatch() and executeBatch() methods. This is much more efficient than executing individual INSERT statements because it reduces the number of round-trips between your application and the database.
The most common and secure way to do this is with a PreparedStatement.
Batch Insert with PreparedStatement
Using PreparedStatement allows you to define a template query and then add multiple sets of parameters to a single batch.
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCBatchInsert {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_db";
String user = "user";
String password = "password";
String sql = "INSERT INTO employees (name, department) VALUES (?, ?)";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// 1. Disable auto-commit for better performance and transaction control
conn.setAutoCommit(false);
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
// Add first record to batch
pstmt.setString(1, "Alice");
pstmt.setString(2, "Engineering");
pstmt.addBatch();
// Add second record to batch
pstmt.setString(1, "Bob");
pstmt.setString(2, "Marketing");
pstmt.addBatch();
// 2. Execute the batch
int[] results = pstmt.executeBatch();
// 3. Commit the transaction
conn.commit();
System.out.println("Batch executed. Rows affected: " + results.length);
} catch (SQLException e) {
// Rollback in case of error
conn.rollback();
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Key Considerations
setAutoCommit(false): By default, JDBC commits every statement individually. Turning this off allows the entire batch to be treated as a single transaction, which significantly boosts performance.addBatch(): Adds the current set of parameters to the internal list of commands.executeBatch(): Sends all the gathered commands to the database. It returns anint[]where each element represents the update count for the corresponding command in the batch.- Batch Size: For very large datasets (e.g., thousands of rows), don’t add everything to a single batch. Instead, execute the batch every 500–1000 rows to avoid memory issues:
if (count % 1000 == 0) { pstmt.executeBatch(); conn.commit(); // Optional: commit periodically }
Using Statement
While possible, using Statement.addBatch(String sql) is generally discouraged for inserts involving variables because it is vulnerable to SQL injection and harder for the database to optimize. Use PreparedStatement whenever possible.
