1

This question should be simple and it may annoy , but still I got this doubt about closing of Result Set using Java. It should be done for each statement or result set should be closed only in final?

       try {
        Class.forName(<driver class>);                
        con = DriverManager.getConnection(
            "IP", 
            "username",
            "password");
        for(String dealId : items) {
            String sql= "SQL Query";
            preparedStatement = con.prepareStatement(sql);
            rs = preparedStatement.executeQuery();
            while(rs.next()) {
                count += rs.getInt("total");                    
            }
            // Result should be closed here as the statement got executed?
        }
        System.out.println(count);
        if(items.size() == count) {
            dealsBelongToTheParty = true;
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        rs.close(); // Or this is right?
        preparedStatement.close();
        if(!con.isClosed())
            con.close();
    }
Aliy
  • 187
  • 11

2 Answers2

2

I suggest to use Java 7 try-with-resources
(the code below assumes that the loop var dealId is used in the query)

Class.forName(<driver class>);                
try (Connection con = DriverManager.getConnection(
        "IP", "username", "password")) {
    for(String dealId : items) {
        String sql= "SQL Query with " + dealId;
        // resources are opened by order 
        try (PreparedStatement preparedStatement = con.prepareStatement(sql);
             ResultSet rs = preparedStatement.executeQuery()) {
            while(rs.next()) {
                count += rs.getInt("total");                    
            }
        } // resources are implicitly closed in reverse order of open
    }
} catch (Exception e) {
    e.printStackTrace();
}

System.out.println(count);
if(items.size() == count) {
    dealsBelongToTheParty = true;
}
Sharon Ben Asher
  • 13,127
  • 5
  • 31
  • 44
0

https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html

"A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results."

So, you shouldn't worry about closing ResultSet.

DDovzhenko
  • 1,255
  • 1
  • 12
  • 33