試讀章節
都會公共圖書館正推出「先試讀再借閱」的方案,以提升借閱量。讀者現在可以先在線上閱讀書籍的第一章,再決定是否實體借閱。早期測試顯示,這個功能讓借閱量提升了 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!");
}
}
}