I have wondered for a long time why the JDBC API provides an autocommit mode (java.sql.Connection.setAutocommit()
). It seems like an attractive nuisance that just lures people into trouble. My theory is it was only added to JDBC in order to simplify life for vendors who wanted to create tools for editing and running SQL using JDBC. Is there any other reason to turn on autocommit, or is it always a mistake?
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.
The statement con. setAutoCommit(true); enables auto-commit mode, which means that each statement is once again committed automatically when it is completed. Then, you are back to the default state where you do not have to call the method commit yourself.
In these cases, the commit occurs when all results and output parameter values have been retrieved. When the autocommit mode is false, the JDBC driver will implicitly start a new transaction after each commit. If this method is called during a transaction, the transaction is committed.
setAutoCommit(true) automatically calls the method or will it be still connection.
Only reasonable reason I can see is to get rid of the connection.commit()
and connection.rollback()
boilerplate in simple single-query transactions in small applications. JDBC in raw form requires by itself already a lot of boilerplate. Every line less makes JDBC less scary to starters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With