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

Viewed 47

I try to get certain data from the database using the following code:

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

The ResultSet (rs valuable) is always null after execution of this code. Usage of rs.next() command leads to NullPointerException. I know that the database contains the data I need and that the connection is set (execute() method returns true and I double-checked connection using my IDE facilities). The driver I installed in pom.xml:

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

What can be the problem and how can I solve it?

1 Answers

You forgot to execute the statement:

statement.execute();

after preparing the statement and before retrieving the result set.

You can execute and fetch the result set in one go with a call to PreparedStatement#executeQuery.

ResultSet rs = statement.executeQuery();
Related