Zacznij terazZacznij za darmo

Sorting the data

CityBook Libraries' search feature works well, but users want to sort results by publication year in either ascending or descending order. You'll build the query dynamically to handle both sort directions.

The HikariSetup class is already configured for you.

To ćwiczenie jest częścią kursu

Querying a PostgreSQL Database in Java

Zobacz kurs

Instrukcje do ćwiczenia

  • Complete the query to sort the result by the publication_year.
  • Extend the query to sort in ascending or descending order depending on the ascending variable representing the user input.

Interaktywne ćwiczenie praktyczne

Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.

public class Main {
    public static void main(String[] args) throws SQLException {
        HikariDataSource ds = HikariSetup.createDataSource();
        
        boolean ascending = true;
        
        // Order by the publication_year in ascending order
        String query = """
            SELECT *
            FROM books
            WHERE publication_year >= ?
                AND status = 'available'
            ____ ____ ____
            """;
        
        // Sort depending on the ascending parameter
        query += ____ ? "____" : "____";
        
        try (Connection conn = ds.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(query)) {
            pstmt.setInt(1, 2000);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    System.out.printf("ID: %d, Title: %s (%d)%n", rs.getInt("book_id"), rs.getString("title"), rs.getInt("publication_year"));
                }
            }
        }
    }
}
Edytuj i uruchom kod