Take the 2-minute tour ×
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. It's 100% free, no registration required.

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
add comment

1 Answer

up vote 3 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
1  
"Explicit is better than implicit" - Thanks. –  Adam Matan Nov 27 '12 at 10:00
add comment

Your Answer

 
discard

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.