LoslegenKostenlos loslegen

Reading sample chapters

The Metropolitan Public Library's "Try Before You Borrow" feature is successfully storing sample chapters. Now you need to implement the retrieval functionality so patrons can actually read these previews on the library's website.

Since sample chapters can contain thousands of characters, you'll use streaming to read the data efficiently. Instead of loading entire chapters into memory at once, you'll read them in small chunks using a character buffer.

Diese Übung ist Teil des Kurses

Querying a PostgreSQL Database in Java

Kurs anzeigen

Anleitung zur Übung

  • Read the stream from the result set for the sample_chapter column.
  • Set the buffer size to read 30 characters.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

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));
            }
        }
    }
}
Code bearbeiten und ausführen