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
  •  | 
  •  

Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top