I would like to ask for help.
I need the method to return results. But I get an exception: java.sql.SQLException: Operation not allowed after ResultSet closed
public class A implements AutoCloseable {
protected Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
public ResultSet GetResultSet() {
ResultSet resultSet = null;
try (Connection connection = getConnection()) {
Statement statement = connection.createStatement();
if (statement.execute(SELECT_ALL_USERS)) {
resultSet = statement.getResultSet();
}
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
@Override
public void close() throws SQLException {
}
}
I don't know what to do. Where is the problem? Do you give me any hint of which way ?
Your help would be greatly appreciated.
Maybe I should override the next() method from the ResultSet interface. But I don't know how to do it.
You use the try-with-resources statement to get the connection:
try (Connection connection = getConnection()) {
The whole point of that statement is to close the connection at the end. And closing the connection also closes its statements and result sets.
Don't return a ResultSet
. Return a List
of objects.
And please, respect the Java naming conventions, too.