Here are the most important points about Batch Processing in JDBC.
To perform the batch processing in JDBC, the Statement interface provided two methods.
addBatch() method is used to construct a batch. Constructing a batch means, storing the SQL commands in a buffer, maintained by Statement object.
To execute the batch, we will use the executeBacth() method. When executeBatch() called, then the commands will be transferred at a time as a batch from buffer to database.
While executing the batch in database, in the middle of command fails then all remaining all commands will be cancelled and finally BatchUpdateException will be thrown. So that it is recommended to execute the batch with Transaction Management.
package com.java.session.ninteen;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcBatchProcessExample {
static final String DB_URL = "jdbc:mysql://localhost/emp";
static final String USER = "root";
static final String PASS = "PASSWORD";
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
connection = DriverManager.getConnection(DB_URL, USER, PASS);
statement = connection.createStatement();
statement.addBatch("update emp.employee set first='khan' where id=11 ");
statement.addBatch("insert into emp.employee values(37, 30, 'sadakhat','navab')");
statement.addBatch("delete from emp.employee where id=36");
int[] result = statement.executeBatch();
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum = sum + result[i];
}
System.out.println(sum + " records are effected ");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}