开始使用免费开始使用

章节试读

Metropolitan 公共图书馆正在推出名为 "Try Before You Borrow" 的新功能,以提升图书流通量。读者现在可以先在线阅读图书的第一章,再决定是否线下借阅。早期测试显示,该功能使借阅量提升了 40%。

您的任务是实现后端功能,将试读章节存入数据库。

试读章节数据已为您预加载,其中包含变量 Data.content

本练习是课程的一部分

在 Java 中查询 PostgreSQL 数据库

查看课程

练习说明

  • 使用 charStream 变量中的字符流为预处理语句设置参数。

交互式实操练习

通过完成这段示例代码来试试这个练习。

public class Main {
    public static void main(String[] args) throws SQLException {
        Reader charStream = new StringReader(Data.content);

        HikariDataSource ds = HikariSetup.createDataSource();
        String query = """
            INSERT INTO book_content (book_id, sample_chapter) VALUES (?, ?)
            ON CONFLICT (book_id) DO NOTHING
            """;

        try (Connection conn = ds.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(query)) {
            pstmt.setInt(1, 7);
            // Set the sample chapter
            pstmt.____(2, ____);
            pstmt.executeUpdate();
            System.out.println("Inserted book content!");
        }
    }
}
编辑并运行代码