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

后端 未结 5 1662
遇见更好的自我
遇见更好的自我 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:39

    You can assign try block "con" reference to another method reference "connection".

    java.sql.Connection connection = null;
    try (java.sql.Connection con = createConnection())
    {
        connection  = con;
        con.setAutoCommit(false);
        Statement stm = con.createStatement();
        stm.execute(someQuery); // causes SQLException
    }
    catch(SQLException ex)
    {
        connection.rollback();
        // do other stuff
    }
    

提交回复
热议问题