開始使用免費開始

閱讀試讀章節

大都會公共圖書館的「先試讀再借閱」功能已成功儲存試讀章節。現在你需要實作資料擷取,讓讀者能在圖書館網站上實際閱讀這些預覽內容。

由於試讀章節可能包含上千個字元,你會使用串流方式有效率地讀取資料。你不會一次把整個章節載入記憶體,而是用字元緩衝區將內容分成小區塊逐步讀取。

本練習屬於課程

在 Java 中查詢 PostgreSQL 資料庫

檢視課程

練習說明

  • 從結果集讀取 sample_chapter 欄位的串流。
  • 將緩衝區大小設為一次讀取 30 個字元。

動手互動練習

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

public class Main {
    public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
        HikariDataSource ds = HikariSetup.createDataSource();
        String query = """
            SELECT book_id, sample_chapter FROM book_content bc
            """;
        try (Connection conn = ds.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(query);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
				// Read the stream from the result set
                ____ reader = rs.____("sample_chapter");
                // Read the first 30 characters
                char[] cb = new ____[____];
                reader.read(cb);
                System.out.printf("Book Id: %d, sample chapter: %s ...\n", rs.getInt("book_id"), new String(cb));
            }
        }
    }
}
編輯並執行程式碼