views:

1683

answers:

3

Does Java Connection.close rollback into a finally block?.

I know .Net SqlConnection.close does it.

With this I could make try/finally blocks without catch...

Example:

try {
    conn.setAutoCommit(false);
    ResultSet rs = executeQuery(conn, ...);
    ....
    executeNonQuery(conn, ...);
    ....

    conn.commit();
} finally {
   conn.close();
}
+7  A: 

According to the javadoc, you should try to either commit or roll back before calling the close method. The results otherwise are implementation-defined.

Joel
+1  A: 

Oracle's JDBC driver commits on close() by default. You should not rely on this behaviour if you intend to write multi-platform JDBC code.

Mr. Shiny and New
A: 

In any database system I've worked with, there is no harm in doing a rollback right after the commit, so if you commit in the try block, and rollback in the finally, things get committed, whereas if an exception or early return causes the commit to be missed, the rollback will rollback the transaction. So the safe thing to do is

try {
    conn.setAutoCommit(false);
    ResultSet rs = executeQuery(conn, ...);
    ....
    executeNonQuery(conn, ...);
    ....

    conn.commit();
} finally {
   conn.rollback();
   conn.close();
}
Paul Tomblin