Home >>Java JDBC Tutorial >JDBC Batch Processing
JDBC Batch Processing basically permits the user to group related SQL statements into a batch and then submit them with only one call to the database.
In batch processing, whenever the programmer sends several SQL statements to the database at once then the programmer will reduce the amount of communication overhead that will result in the enhanced performance.
Here is a typical sequence of the steps that can be used to use Batch Processing with the Statement Object as followed:
Here is an example of the above mentioned concept that will depict the process of batch update using Statement object:
//First Create statement object
Statement stmt = conn.createStatement();
//Here Set auto-commit to false
conn.setAutoCommit(false);
//Create SQL statement
String SQL = "INSERT INTO Students(id, firstname, lastname, age) " +
"VALUES(100,'abhi', 'kumar', 30)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create one more SQL statement
String SQL = "INSERT INTO Students (id, firstname, lastname, age) " +
"VALUES(101,'Rexx', 'Singh', 35)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create one more SQL statement
String SQL = "UPDATE Students SET age = 35 " +
"WHERE id = 100";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create an int[] to hold returned values
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();
Here is a typical sequence of the steps that can be used to use Batch Processing with the PrepareStatement Object as followed:
Here is an example of the above mentioned concept that will be depicting the process of a batch update using PrepareStatement object:
// Create SQL statement
String SQL = "INSERT INTO Students (id, firstname, lastname, age) " +
"VALUES(?, ?, ?, ?)";
// Create PrepareStatement object
PreparedStatemen pstmt = conn.prepareStatement(SQL);
//Set auto-commit to false
conn.setAutoCommit(false);
// Set the variables
pstmt.setInt( 1, 100 );
pstmt.setString( 2, "Abhi" );
pstmt.setString( 3, "kumar" );
pstmt.setInt( 4, 30 );
// Add it to the batch
pstmt.addBatch();
// Set the variables
pstmt.setInt(1, 101 );
pstmt.setString(2, "Rexx" );
pstmt.setString(3, "Singh" );
pstmt.setInt(4, 35 );
// Add it to the batch
pstmt.addBatch();
//add more batches
.
.
.
//Create an int[] to hold returned values
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();