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.
本练习是课程的一部分
Querying a PostgreSQL Database in Java
练习说明
- Read the stream from the result set for the
sample_chaptercolumn. - Set the buffer size to read 30 characters.
交互式实操练习
通过完成这段示例代码来试试这个练习。
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));
}
}
}
}