Transaction rollback on SQLException using new try-with-resources block

后端 未结 5 1659
遇见更好的自我
遇见更好的自我 2020-12-12 19:21

I have a problem with try-with-resources and I am asking just to be sure. Can I use it, if I need to react on exception, and I still need the resource in catch block? Exampl

5条回答
  •  一整个雨季
    2020-12-12 19:45

    In the example above I think it's better to put con.commit() inside nested try-catch because it also can throw SQLException.

     try (java.sql.Connection con = createConnection())
        {
            con.setAutoCommit(false);
            try (Statement stm = con.createStatement())
            {
                stm.execute(someQuery); // causes SQLException
                con.commit();           // also causes SQLException!
            }
            catch(SQLException ex)
            {
                con.rollback();
                throw ex;
            }finally{
                con.setAutoCommit(true);
            }
        }
    

    We had such problem in our production environment with unclosed sessions.

提交回复
热议问题