Zacznij terazZacznij za darmo

Prepared Statements

After discovering the SQL injection vulnerability, CityBook Libraries needs you to secure the book search feature. You'll switch from simple Statement objects to PreparedStatement to prevent injection attacks.

The HikariSetup class is already configured.

To ćwiczenie jest częścią kursu

Querying a PostgreSQL Database in Java

Zobacz kurs

Instrukcje do ćwiczenia

  • Use a placeholder for the title parameter.
  • Create a PreparedStatement from the connection.
  • Set the title parameter for the prepared statement.

Interaktywne ćwiczenie praktyczne

Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.

public class Main {
    public static void main(String[] args) throws SQLException {
        HikariDataSource ds = HikariSetup.createDataSource();
        // Set the parameter in the query
        String query = "SELECT * FROM books WHERE title = ____";
        // Create the prepared statement
        try (Connection conn = ds.getConnection();
            PreparedStatement pstmt = ____.____(query)) {
            // Set the title parameter
            pstmt.____(____, "Clean Code");
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    System.out.printf("ID: %d, Title: %s (%d)%n", rs.getInt("book_id"), rs.getString("title"), rs.getInt("publication_year"));
                }
            }
        }
    }
}
Edytuj i uruchom kod