开始使用免费开始使用

读取示例章节

都市公共图书馆的 "Try Before You Borrow" 功能已成功存储示例章节。现在需要实现检索功能,方便读者在图书馆网站上实际阅读这些预览内容。

由于示例章节可能包含成千上万的字符,您将使用流式读取来提高效率。与一次性将整章加载到内存不同,您会使用字符缓冲区,将内容按小块读取。

本练习是课程的一部分

在 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));
            }
        }
    }
}
编辑并运行代码