LoslegenKostenlos loslegen

Sample chapters

The Metropolitan Public Library is launching a "Try Before You Borrow" initiative to increase circulation. Patrons can now read the first chapter of books online before deciding to check them out physically. Early testing revealed that this feature increased checkouts by 40%.

Your task is to implement the backend functionality to store sample chapters in the database.

The sample chapter, which includes the Data.content variable, has been preloaded for you.

Diese Übung ist Teil des Kurses

Querying a PostgreSQL Database in Java

Kurs anzeigen

Anleitung zur Übung

  • Set the parameter for the prepared statement with the character stream from the charStream variable.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

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!");
        }
    }
}
Code bearbeiten und ausführen