Prepared Statements
在發現 SQL 注入漏洞之後,CityBook Libraries 需要你強化圖書搜尋功能的安全性。你將把簡單的 Statement 物件改為使用 PreparedStatement,以防止注入攻擊。
HikariSetup 類別已經設定完成。
本練習屬於課程
在 Java 中查詢 PostgreSQL 資料庫
練習說明
- 使用一個佔位符作為 title 參數。
- 從連線建立一個
PreparedStatement。 - 為預備敘述設定
title參數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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"));
}
}
}
}
}