Get startedGet started for free

Books report

CityBook Libraries wants to generate a catalog report showing their book collection. You'll use HikariCP connection pooling to fetch data efficiently from the PostgreSQL database.

The query selects book_id, title, and publication_year from the books table. Put together everything you've learned: get a pooled connection, create a statement, execute the query, and extract the results. The HikariSetup class and HikariDataSource are already imported for you.

This exercise is part of the course

Querying a PostgreSQL Database in Java

View Course

Exercise instructions

  • Get a connection from the data source using getConnection().
  • Create a statement with createStatement().
  • Execute the query using executeQuery(query).
  • Use the correct getter methods for book_id and title.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

public class Main {
    public static void main(String[] args) throws SQLException {
        HikariDataSource ds = HikariSetup.createDataSource();

        String query = "SELECT b.book_id, b.title, b.publication_year FROM books b LIMIT 5";

        // Get connection, create statement, and execute query
        try (Connection conn = ____.____();
        Statement stmt = ____.____();
        ResultSet rs = ____.____(query)) {
            while (rs.next()) {
                // Retrieve integer column
                int bookId = rs.____("book_id");
                // Retrieve string column
                String title = rs.____("title");
                int year = rs.getInt("publication_year");
                System.out.printf("ID: %d, Title: %s (%d)%n", bookId, title, year);
            }
        }
    }
}
Edit and Run Code