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.
This exercise is part of the course
Querying a PostgreSQL Database in Java
Exercise instructions
- Read the stream from the result set for the
sample_chaptercolumn. - Set the buffer size to read 30 characters.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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));
}
}
}
}