Nick Richardson
Nick Richardson

Reputation: 187

Closing Connection, PreparedStatement, and ResultSet all in one call

Is there anything wrong in closing my connection resources like this? I seem to still have idle connections in postgres running.

public void doSomething(){
  Connection con = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  try{
    con = getConnection();
    ps = con.prepareStatement("sql here");
    ....
    rs = ps.executeQuery();
    ...
   } catch(Exceptions stuff){
   } finally {
     closeAll(con,ps,rs);
   }
}
public void closeAll(Connection con, PreparedStatement ps, ResultSet rs){
  try{
        if(rs != null){
            rs.close();
        }
        if(ps != null){
            ps.close();
        }
        if(con != null){
            con.close();
        }
    } catch(SQLException e){
        ....
    }
}

Upvotes: 1

Views: 859

Answers (1)

Hello_JAVA
Hello_JAVA

Reputation: 96

Practice the Best Practice

Yes, their is a problem in closing connection the way you have closed.

Suppose, an exception occurred while closing ResultSet object the rest things would not be closed

Second, suppose if everything goes fine, still you are holding other connection (etc) you are not using, it adds to the burden to the JVM, Database, Memory manager etc

It is recommended to use " try(){} with resource " feature available in JAVA 7 or if you are using JAVA 6 close them when it is no longer needed.

Upvotes: 2

Related Questions