How to Correctly Close Resources

前端 未结 6 1417
孤独总比滥情好
孤独总比滥情好 2020-12-09 16:48

As I was cleaning up some code, FindBugs pointed me to a bit of JDBC code that uses Connection, CallableStatement, and ResultSet objects. Here\'s a snippet from that code:

6条回答
  •  有刺的猬
    2020-12-09 17:39

    I think the best answer has already being mentioned, but I thought it could be interesing to mention that you could consider the new JDK 7 feature of autoclosable resources.

    try{
        try(Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/hrdb", "obiwan", "kenobi"); 
            Statement stm = conn.createStatement(); 
            ResultSet rs = stm.executeQuery("select name from department")) {
    
            while(rs.next()){
                System.out.println(rs.getString("name"));
            }
    
        } 
    }catch(SQLException e){
        //you might wanna check e.getSuppressed() as well
        //log, wrap, rethrow as desired.
    }
    

    Not all of us can migrate to JDK 7 now, but for those who can start playing with the developer preview, this offer an interesting way of doing things and certainly may deprecate other approaches in the near future.

提交回复
热议问题