Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is rollback needed if java.sql.Connection#commit() throws exception?

According to JAVA documentation, Connection#commit() can throw SQLException. My question is whether or not a rollback should still be issued in this scenario.

For example:

Connection con = null;
try {
    // assume this method returns an opened connection with setAutoCommit(false)
    con = createConnection(); 

    // do DB stuff

    con.commit();
} catch (SQLException e) {
    if (con != null) {
        // what if con.commit() failed, is this still necessary,
        // will it hurt anything?
        con.rollback();
    }
} finally {
    if (con != null) {
        con.close();
    }
}

I actually wrapped the con.rollback() call into another method which ignores any exceptions thrown by it, so I think I'm ok here. I just wondered if this was the best way of handling things.

like image 513
dcp Avatar asked Sep 24 '10 20:09

dcp


People also ask

What is the use of rollback () method in JDBC?

Undoes all changes made in the current transaction and releases any database locks currently held by this SQLServerConnection object.

Can we rollback the transaction in JDBC?

If a commit succeeds then its done, complete, you can't roll it back at that point. You have to mark a transaction for rollback before calling the commit method.


1 Answers

Rollback is important even if commit failed, according to the Java 1.6 JDBC docs:

It is strongly recommended that an application explicitly commits or rolls back an active transaction prior to calling the close method. If the close method is called and there is an active transaction, the results are implementation-defined.

This means that if you do not explicitly invoke rollback, some JDBC implementation might invoke commit before closing the connection.

Another good reason to rollback is as Xepoch suggested and when using a connection pool it is even more important. When getting a connection from a connection pool, most implementations will execute connection.setAutoCommit(defaultAutoCommit) before giving you the connection and according to the JavaDocs:

If this method is called during a transaction and the auto-commit mode is changed, the transaction is committed

If the connection.rollback() throws an exception - then it is a tricky one...

like image 130
MosheElisha Avatar answered Oct 14 '22 06:10

MosheElisha