Get startedGet started for free

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.

This exercise is part of the course

Querying a PostgreSQL Database in Java

View Course

Exercise instructions

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

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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!");
        }
    }
}
Edit and Run Code