Does calling close on a ResultSet reference close the another reference referring to the same ResultSet?

StackOverflow https://stackoverflow.com/questions/23470278

  •  15-07-2023
  •  | 
  •  

I have a Servlet, which uses a static utility method that returns a ResultSet.

In my Servlet code I have

ResultSet rs = SimpleSearch.searchByName(request);

In my searchByName method, I have the following code(Not full Code);

try {
            preparedStatement = connection.prepareStatement(str);
            preparedStatement.setDate(1, firstSQLDOB);
            preparedStatement.setDate(2, secondSQLDOB);
            rs = preparedStatement.executeQuery();
            resultSet = rs;

        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return resultSet;

Does closing rs also close resultSet?

有帮助吗?

解决方案

Yes, since resultSet and rs are two references pointing to the same object.

I wouldn't pass around your resultset normally since you want to control the closure of it (and prevent a resource leak). I would rather get it, iterate through and build a set of objects relating to its results, close the result set and hand back your resultant collection of objects from the database.

其他提示

It's the same ResultSet. You closed it: it's closed. There's no such thing as closing separate references to the same object.

Does closing rs also close resultSet?

Yes. You are right. It closes, since they pointing to same reference.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top