【问题标题】:ResultSet is null while the connection is active and the database works properly [closed]连接处于活动状态且数据库正常工作时,ResultSet 为 null [关闭]
【发布时间】:2021-10-31 07:27:51
【问题描述】:

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

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();

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

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

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

【问题讨论】:

  • 你需要执行准备好的语句。

标签: java postgresql jdbc


【解决方案1】:

你忘了执行语句:

statement.execute();

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

您可以通过调用PreparedStatement#executeQuery 一次性执行和获取结果集。

ResultSet rs = statement.executeQuery();

【讨论】:

  • 非常感谢!完全正确。
猜你喜欢
  • 2010-11-19
  • 2019-09-28
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多