tdutyui
tdutyui

Reputation: 3

ResultSet is not related to table

String url = "jdbc:postgresql://localhost:5432/OilPrice";
Connection connection;
{
    try {
        connection = DriverManager.getConnection(url, "postgres", "***");
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }
}

@RequestMapping(path = "/data")
@GetMapping
public ResultSet allData() throws SQLException {
    PreparedStatement statement = connection.prepareStatement("SELECT * FROM oilprice");
    ResultSet rs = statement.executeQuery();
    return rs;
}

When I execute this method I get very many strings like this in my browser and I get it from literally any query:

{"statement":{"poolable":true,"closeOnCompletion":false,"wantsGeneratedKeysAlways":false,"connection":{"clientInfo":{"ApplicationName":"PostgreSQL JDBC Driver"},"queryExecutor"

Also when I tried convert ResultSet I got JSON {"empty":false}. Connection is right, because I insert data to db from Java. What's the problem?

Upvotes: 0

Views: 58

Answers (1)

aeberhart
aeberhart

Reputation: 889

You are getting a JSON version of the ResultSet implementation of the Postgres JDBC driver. To get the table contents, you need to iterate over rs:

List<Map<String, Object>> data = new ArrayList<>();
ResultSetMetaData m = rs.getMetaData();
while (rs.next()) {
  Map<String, Object> row = new LinkedHashMap<>();
  for (int c = 1; c <= m.getColumnCount(); c++)
    row.put(m.getColumnLabel(c), res.getObject(c));
  data.add(row);
}
return data;

Note that this will load the entire table into RAM. If the table is very large, you should use SQL limit / offset to page through the results.

Upvotes: 2

Related Questions