Prepared Statement
Sau khi phát hiện lỗ hổng SQL injection, CityBook Libraries cần bạn bảo mật tính năng tìm kiếm sách. Bạn sẽ chuyển từ Statement đơn giản sang PreparedStatement để ngăn chặn tấn công chèn lệnh.
Lớp HikariSetup đã được cấu hình sẵn.
Bài tập này là một phần của khóa học
Truy vấn cơ sở dữ liệu PostgreSQL trong Java
Hướng dẫn bài tập
- Dùng một placeholder cho tham số title.
- Tạo
PreparedStatementtừ connection. - Gán tham số
titlecho prepared statement.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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"));
}
}
}
}
}