当连接处于活动状态且数据库正常工作时,ResultSet 为空

ResultSet is null while the connection is active and the database works properly

我尝试使用以下代码从数据库中获取某些数据:

Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "username", "pwd");
System.out.println("Successfully set!");
PreparedStatement statement = connection.prepareStatement("SELECT * FROM ABSTR_CARS");
ResultSet rs = statement.getResultSet();

执行此代码后,结果集(rs 有价值)始终为空。使用 rs.next() 命令会导致 NullPointerException。我知道数据库包含我需要的数据并且连接已设置(execute() 方法 returns true 并且我使用我的 IDE 设施仔细检查了连接)。 我安装的驱动在pom.xml:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.23</version>
</dependency>

可能是什么问题,我该如何解决?

您忘记执行语句:

statement.execute();

在准备语句之后和检索结果集之前。

您可以通过调用 PreparedStatement#executeQuery.

一次性执行并获取结果集
ResultSet rs = statement.executeQuery();