開始使用免費開始

圖書搜尋系統

CityBook Libraries 目前的搜尋功能只支援完全相同的書名。它們需要更有彈性的搜尋功能,讓訪客可以用部分書名、作者姓名,或兩者的任意組合來搜尋。

你將建立一個動態查詢產生器,會依使用者提供的搜尋條件來組出 SQL 查詢。HikariSetup 類別已為你設定完成。

本練習屬於課程

在 Java 中查詢 PostgreSQL 資料庫

檢視課程

練習說明

  • 將書名條件接到查詢字串後面。
  • 視情況把 AND(若已加入書名條件)或 WHERE(若尚未加入)加到查詢中。
  • 完成查詢,讓結果依書名排序。

動手互動練習

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

public class Main {
    public static void main(String[] args) {
        String titleSearch = "first";
        String authorSearch = null;

        StringBuilder sql = new StringBuilder(
                "SELECT b.title, a.first_name AS author " +
                        "FROM books b " +
                        "JOIN book_authors ba ON b.book_id = ba.book_id " +
                        "JOIN authors a ON ba.author_id = a.author_id ");
        boolean hasTitleSearch = false;

        if (titleSearch != null && !titleSearch.isEmpty()) {
            // Append the title condition
            sql.____("WHERE b.title ILIKE ? ");
            hasTitleSearch = true;
        }

        if (authorSearch != null && !authorSearch.isEmpty()) {
            // Add AND if you added title condition or WHERE if not
            sql.append(hasTitleSearch ? "AND " : "____");
            sql.append(" a.first_name ILIKE ? ");
        }

        // Complete the query to sort by title
        sql.append("____ ____ b.title");

        System.out.println(sql);
    }
}
編輯並執行程式碼