Wildcard Queries in Prepared Statements with LIKE
When using prepared statements for database queries, implementing a search functionality with keywords often requires the use of the LIKE operator. This guide provides a comprehensive solution on how to achieve this with prepared statements.
To utilize the LIKE operator with prepared statements, you can append the wildcard symbol (%) to the search term within the value provided to the prepared statement, such as:
String notes = "keyword%"; PreparedStatement pstmt = con.prepareStatement( "SELECT * FROM analysis WHERE notes LIKE ?"); pstmt.setString(1, notes); ResultSet rs = pstmt.executeQuery();
By setting the value with the appended wildcard, you enable a query that matches all records where the "notes" column contains the input keyword as a substring.
However, certain characters have special meanings in SQL, including %, !, [, _, and ]. To ensure proper handling of these characters, they should be escaped using the ESCAPE clause in the prepared statement. For instance:
String notes = "keyword%" .replace("!", "!!") .replace("%", "!%") .replace("_", "!_") .replace("[", "!["); PreparedStatement pstmt = con.prepareStatement( "SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'"); pstmt.setString(1, notes + "%");
By replacing these characters with their escaped versions, the prepared statement will correctly interpret the wildcard and match records accordingly.
Depending on your search requirements, you can adjust the placement of the wildcard to achieve different matching scenarios:
以上是如何在 LIKE 準備語句中使用通配符?的詳細內容。更多資訊請關注PHP中文網其他相關文章!