JDBC Batch Update in Java: Statement vs PreparedStatement with Advantages and Working
JDBC Batch Update in Java
Batch Update in JDBC is a process where multiple SQL queries are grouped together and sent to the database server in a single request.
Instead of executing SQL queries one by one, batch update improves performance and efficiency by reducing network traffic between the Java application and the database server.
✅ Why Use Batch Update?
- 🚀 Improves application performance
- 🌐 Reduces network calls to the database
- 📉 Minimizes database load
- 🧠 Efficient for bulk insert, update, and delete operations
Real-Life Example:
When inserting thousands of student records or updating employee salaries in bulk, batch update is the best approach.
🔹 Batch Update Using Statement
Batch update can be performed using the Statement interface in the following way:
Steps:
- Create a Statement object.
- Create a batch.
- Add SQL queries (similar or dissimilar) to the batch.
- Execute the batch.
Important Methods:
- addBatch(String query)
- Adds an SQL query to the batch.
- This method is declared in the Statement interface, and its implementation is provided by the database vendor inside the driver JAR file.
- executeBatch()
- Executes all SQL queries in the batch at once.
Return Type:
- int[] → Each element represents the number of rows affected by each SQL query (INSERT / UPDATE / DELETE).
🔹 Batch Update Using PreparedStatement
Batch update using PreparedStatement is more efficient and secure compared to Statement.
Key Points:
- Used when SQL queries are similar.
- Prevents SQL Injection.
- Improves performance due to precompiled SQL.
Steps:
- Create a PreparedStatement with a parameterized SQL query.
- Set values for parameters.
- Add the query to the batch using addBatch().
- Repeat for multiple records.
- Execute the batch using executeBatch().
Important Methods:
addBatch()
- Adds the prepared SQL query with current parameter values to the batch.
executeBatch()
- Executes all batch queries together.
Return Type:
- int[] → Number of rows affected for each batch execution.
🔍 Statement vs PreparedStatement (Batch Update)
Feature. Statement. PreparedStatement
SQL Type. Similar & Dissimilar. Similar only
Performance. Moderate. High
Security. Less secure. Highly secure
SQL Injection. Possible. Prevented
Recommended. No. Yes
📌 Key Points for Exams & Interviews
- Batch update sends multiple SQL queries at once
- Reduces network traffic
- Supported by Statement and PreparedStatement
- executeBatch() returns int[]
- Vendor provides implementation via JDBC driver
- Best suited for bulk database operations
Comments
Post a Comment