I want to send two different prepared statements in one single batch.
Currently I am doing this in two as you can see in the commented lines and it works,
I am trying to utilize prepared statements and a batch! I say statements because I would like to send two prepared statements in one batch.
When you're talking of PreparedStatement, a batch is associated with this PreparedStatement object's batch of commands and NOT the other way round. You should look at the javadoc for addBatch()
method to know more about this.
So in your case, here's what I would have done:
So your code would look something like this:
preparedStatementWithdraw = connection.prepareStatement(....);
preparedStatementDeposit = connection.prepareStatement(....);
boolean autoCommit = connection.getAutoCommit();
int batchLimit = 1000; //limit that you can vary
int batchCounter = 0;
try{
connection.setAutoCommit(false);
//set the params and start adding your batch statements, as per your requirement, something like
preparedStatementWithdraw.addBatch();
preparedStatementDeposit.addBatch();
batchCounter++;
if(batchCounter == batchLimit){
try{
preparedStatementWithdraw.executeBatch();
preparedStatementDeposit.executeBatch();
}catch(Exception exe){
//log your error
}finally{
preparedStatementWithdraw.clearBatch();
preparedStatementDeposit.clearBatch();
batchCounter = 0;
}
}
}finally{
//process if any more statements are remaining in the batch
try{
preparedStatementWithdraw.executeBatch();
preparedStatementDeposit.executeBatch();
}catch(Exception exe){
//log your error
}finally{
preparedStatementWithdraw.clearBatch();
preparedStatementDeposit.clearBatch();
}
//1. depending on your requirement, commit/rollback the transation
//2. Set autocommit to its original value
connection.setAutoCommit(autoCommit);
//3. Resoure management statements
}