Does Java Connection.close rollback?

后端 未结 6 1145
别跟我提以往
别跟我提以往 2020-12-05 19:36

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..

6条回答
  •  孤街浪徒
    2020-12-05 19:55

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

提交回复
热议问题