Khái niệm
Batch Update là kỹ thuật gom nhiều câu lệnh SQL (INSERT/UPDATE/DELETE) và thực thi cùng một lần để giảm round-trip đến database, tăng hiệu năng.
Parameterized Batch Update sử dụng PreparedStatement với các placeholder (?) và gán giá trị qua setter, sau đó add vào batch. Cách này an toàn chống SQL Injection và tái sử dụng plan thực thi.
Các bước thực hiện
- Tắt auto-commit:
conn.setAutoCommit(false) - Tạo
PreparedStatementvới câu SQL có placeholder. - Với mỗi bộ dữ liệu: set giá trị →
addBatch(). - Thực thi:
executeBatch()trả về mảng int (số dòng ảnh hưởng mỗi câu). - Commit:
conn.commit().
Ví dụ hoàn chỉnh
import java.sql.*;
public class ParameterizedBatchUpdate {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testDB";
String user = "root";
String pass = "password";
try (Connection conn = DriverManager.getConnection(url, user, pass)) {
conn.setAutoCommit(false);
String sql = "INSERT INTO Sales (Product_Name, Name_Of_Customer, Month_Of_Dispatch, Price, Location) VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
// Batch 1
ps.setString(1, "Keyboard");
ps.setString(2, "Amith");
ps.setString(3, "January");
ps.setInt(4, 1000);
ps.setString(5, "Hyderabad");
ps.addBatch();
// Batch 2
ps.setString(1, "Earphones");
ps.setString(2, "Sumith");
ps.setString(3, "March");
ps.setInt(4, 500);
ps.setString(5, "Vishakhapatnam");
ps.addBatch();
// Batch 3
ps.setString(1, "Mouse");
ps.setString(2, "Sudha");
ps.setString(3, "September");
ps.setInt(4, 200);
ps.setString(5, "Vijayawada");
ps.addBatch();
int[] results = ps.executeBatch();
conn.commit();
System.out.println("Đã insert " + results.length + " bản ghi");
for (int i = 0; i < results.length; i++) {
System.out.println("Batch " + i + ": " + results[i] + " row(s)");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Kết quả mong đợi
Đã insert 3 bản ghi
Batch 0: 1 row(s)
Batch 1: 1 row(s)
Batch 2: 1 row(s)
Lợi ích
- Giảm overhead network (một lần round-trip cho nhiều câu lệnh).
- Chống SQL Injection nhờ PreparedStatement.
- Database có thể tối ưu execution plan cho statement lặp lại.
- Dễ dàng xử lý transaction (commit/rollback toàn bộ batch).
Lưu ý
- Kích thước batch quá lớn có thể gây OOM hoặc lock lâu; nên chia nhỏ (ví dụ 1000-5000 câu/batch).
- Một số driver JDBC không hỗ trợ batch thật sự, chỉ chạy tuần tự.