開始使用免費開始

篩選資料

CityBook Libraries 希望使用者能依出版年份搜尋可借的書籍。使用者會輸入一個年份,系統應回傳所有在該年份或之後出版、且目前可借的書。

你將使用預備語句的安全做法。HikariSetup 類別已經為你設定好了。

本練習屬於課程

在 Java 中查詢 PostgreSQL 資料庫

檢視課程

練習說明

  • 撰寫 WHERE 子句,以查詢出版年份大於或等於某個佔位符的書籍。
  • status 篩選,只允許 'available' 的書。
  • 設定預備語句中的出版年份參數。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class Main {
    public static void main(String[] args) throws SQLException {
        HikariDataSource ds = HikariSetup.createDataSource();
        // Complete the query to filter the data based on the requirements.
        String query = "SELECT * FROM books ____ publication_year >= ____ AND status = '____'";
        try (Connection conn = ds.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(query)) {
            // Set the publication year parameter
            ____.____(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"));
                }
            }
        }
    }
}
編輯並執行程式碼