Automating Resource Management in Java





One day ago, my friend "Nazareno" showed me his code of how to call a database function and it had a structure like this:




Try-with-resources

The problem with it code is that only is managing the automatic close connection with the try-with-resources:

In it new try all the resources are closed in the reverse of the order in which they are created.  Then an improvement to it code should be:

try (var conn = ds.getConnection(); var cs = conn.prepareCall(sql)) {
        
       .... code supressed ....

      try(var rs = cs.executeQuery()){
          .... code supressed ....
     }
}

Stop doing this:


rs.close();

cs.close();

While it is a good habit to close all the three resources, it isn't strictly necessary. Closing a JDBC resource should close any resources that is created. In theory it should happens:

  • Closing a connection also closes PreparedStatement (or CallableStatement) and ResultSet.
  • Closing a PreparedStatement (or CalleStatement) also closes the ResultSet.

 It is important to close resources in the right order. This avoids both resource leaks and exceptions.


Bonus


Use SQL Exception instead Exception and get more information:

         ...


         } catch (SQLException e) {


            System.out.println(e.getMessage());


            System.out.println(e.getSQLState());


            System.out.println(e.getErrorCode());


         } 

I learned of it experience so much too.

Enjoy!


Joe


 

Share:

0 comentarios:

Publicar un comentario