首頁 > Java > java教程 > 如何在 LIKE 準備語句中使用通配符?

如何在 LIKE 準備語句中使用通配符?

Linda Hamilton
發布: 2024-11-15 12:32:02
原創
889 人瀏覽過

How to Use Wildcards in Prepared Statements with LIKE?

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:

  • Prefix match: "%" appended to the end of the keyword (e.g., "keyword%")
  • Suffix match: "%" prepended to the beginning of the keyword (e.g., "%" + "keyword")
  • Global match: "%" appended to both ends of the keyword (e.g., "%" + "keyword" + "%")

以上是如何在 LIKE 準備語句中使用通配符?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板