Does Java Connection.close rollback?

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();
}


Asked by: Marcus127 | Posted: 28-01-2022






Answer 1

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

Answered by: Chester209 | Posted: 01-03-2022



Answer 2

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();
}

Answered by: Ted779 | Posted: 01-03-2022



Answer 3

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.

Answered by: Robert662 | Posted: 01-03-2022



Answer 4

The behavior is completely different between different databases. Examples:

Oracle

The transaction is committed when closing the connection with an open transaction (as @Mr. Shiny and New 安宇 stated.

SQL Server

Calling the close method in the middle of a transaction causes the transaction to be rolled back.

close Method (SQLServerConnection)

Answered by: David571 | Posted: 01-03-2022



Answer 5

For MySQL JDBC, the implementation rolls back the connection if closed without a call to commit or rollback methods.

Answered by: Julian159 | Posted: 01-03-2022



Answer 6

It is useless to rollback in finally block. After you commit, and commit is successful, why to roll back? So if i were you, i would rollback in catch block.

Answered by: Wilson766 | Posted: 01-03-2022



Similar questions

java - SQL: connection.close - Need some hints for a excerice

I became a hint to put in the code a finally statement with a 'connection.close' before the first catch statement appears. I don't see any ways to implement that, could you please give me a short hint how I could handle that?! Many thanks!






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top