Consider the following code snippet.
assume that DbConnector.connectToDb()
returns a valid Connection object and that the contact table has an entry with the value "Michael" in the firstName
column:.
ResultSet resultSet = null; try (Connection connection = DbConnector.connectToDb()) { Statement statement = connection.createStatement(); resultSet = statement.executeQuery("SELECT * FROM contact WHERE firstName LIKE 'M%'"); // #LINE1 } while (resultSet.next()){ //#LINE2 // print the names by calling resultSet.getString("firstName")); }
firstName
column values that start with the character "M".C.
the try-with-resources block is closed before the while statement executes.
Calling resultSet.next()
results in making a call on the closed ResultSet object.
hence, this program results in throwing a SQLException ("operation not allowed after resultset closed").