Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to execute some statements, and commit the entire batch at the end. I've tried the following approach:

connection.setAutoCommit(false);            // Don't commit for each statement
int[] returnCodes = pstmt.executeBatch();   // Execute all statements
connection.setAutoCommit(true);             // Back to normal state - future statements
                                            // will be committed instantly
connection.commit();                        // Commit our batch

Which fails miserably:

java.sql.SQLException: Can't call commit when autocommit=true
--reference to the line with connection.commit()--

What's the right way to go? does connection.setAutoCommit(true) commits all executed batch statements?

share|improve this question
up vote 4 down vote accepted

From the Connection.setAutoCommit docs:

NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is committed. If setAutoCommit is called and the auto-commit mode is not changed, the call is a no-op.

But I don't think it's very readable/obvious in your code. You should probably simply commit before switching back to autocommit mode. Makes the intent clear.

share|improve this answer
"Explicit is better than implicit" - Thanks. – Adam Matan Nov 27 '12 at 10:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.