我想寻求帮助。
我需要返回结果的方法。 但我得到一个异常:java.sql.SQLException:结果集关闭后不允许操作
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 {
}
}
我不知道该怎么办。哪里有问题? 你能给我任何提示吗?
我们将非常感谢您的帮助。
也许我应该重写 ResultSet 接口(interface)中的 next() 方法。但我不知道该怎么做。
最佳答案
您使用 try-with-resources 语句来获取连接:
try (Connection connection = getConnection()) {
该语句的重点是在最后关闭连接。关闭连接也会关闭其语句和结果集。
不要返回ResultSet
。返回对象的列表
。
也请遵守 Java 命名约定。
关于java - 如何返回结果集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59226153/