Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC connection default autoCommit behavior

I'm working with JDBC to connect to Oracle. I tested connection.setAutoCommit(false) vs connection.setAutoCommit(true) and the results were as expected.

While by default connection is supposed to work as if autoCommit(true) [correct me if I'm wrong], but none of the records are being inserted till connection.commit() was called. Any advice regarding default behaviour?

String insert = "INSERT INTO MONITOR (number, name,value) VALUES (?,?,?)";  conn = connection; //connection  details avoided preparedStmtInsert = conn.prepareStatement(insert); preparedStmtInsert.execute();  conn.commit(); 
like image 876
stackex Avatar asked Jun 13 '12 18:06

stackex


People also ask

Is Autocommit true by default?

With these versions of the JDBC driver, the default value for AutoCommit for an XA-enabled data source is true. The value of AutoCommit still defaults to false for an XA-enabled Oracle data source with the Oracle 9.2.

How can you avoid auto-commit mode in JDBC?

Explicit Transaction Management When Auto-Commit Is False We need to disable auto-commit mode when we want to handle transactions ourselves and group multiple SQL statements into one transaction. We do this by passing false to the connection's setAutoCommit method: connection. setAutoCommit(false);

What is connection Autocommit?

If a connection is in autocommit mode, then all its SQL statements are run and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are ended by a call to either the commit method or the rollback method. By default, new connections are in autocommit mode.

Which of following is true about auto-commit mode in JDBC?

If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion.


1 Answers

From Oracle JDBC documentation:

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. (To be more precise, the default is for a SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)

The other thing is - you ommitted connection creation details, so I'm just guessing - if you are using some frameworks, or acquiring a connection from a datasource or connection pool, the autocommit may be turned off by those frameworks/pools/datasources - the solution is to never trust in default settings ;-)

like image 158
npe Avatar answered Oct 06 '22 13:10

npe