Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COMMIT OR conn.setAutoCommit(true)

I have noticed some programmer using COMMIT other using conn.setAutoCommit(true); to end the transaction or roll back so what are the benefits of using one instead of the other?

Where is the main difference?

conn.setAutoCommit(true);

over

statement.executeQuery(query);
statement.commit();
like image 771
Motasem Avatar asked May 04 '12 23:05

Motasem


People also ask

What does setAutoCommit true do?

setAutoCommit(true); enables auto-commit mode, which means that each statement is once again committed automatically when it is completed.

How do I make auto commit to true?

//Setting the auto commit on con. setAutoCommit(true); //Setting the auto commit off con. setAutoCommit(false); Following JDBC program establishes a connection with the database and turns off the auto-commit.

What is setAutoCommit false?

setAutoCommit(false) will allow you to group multiple subsequent Statement s under the same transaction. This transaction will be committed when connection. commit() is invoked, as opposed to after each execute() call on individual Statement s (which happens if autocommit is enabled).

Should autocommit be true or false?

You should set autocommit to true whenever you're issuing database transactions. A database trasaction is a logical unit of work, which usually consists of multiple database operations (usually multiple updates) and you want either all of them to succeed or all of them to fail.


1 Answers

You should in general use Connection.commit() and not Connection.setAutoCommit(true) to commit a transaction, unless you want to switch from using transaction to the 'transaction per statement' model of autoCommit.

That said, calling Connection.setAutoCommit(true) while in a transaction will commit the transaction (if the driver is compliant with section 10.1.1 of the JDBC 4.1 spec). But you should really only ever do that if you mean to stay in autoCommit after that, as enabling / disabling autoCommit on a connection may have higher overhead on a connection than simply committing (eg because it needs to switch between transaction managers, do additional checks, etc).

You should also use Connection.commit() and not use the native SQL command COMMIT. As detailed in the documentation of connection:

Note: When configuring a Connection, JDBC applications should use the appropritate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available.

The thing is that commands like commit() and setAutoCommit(boolean) may do more work in the back ground, like closing ResultSets and closing or resetting Statements. Using the SQL command COMMIT will bypass this and potentially bring your driver / connection into an incorrect state.

like image 158
Mark Rotteveel Avatar answered Sep 26 '22 01:09

Mark Rotteveel