Home > Java > javaTutorial > body text

How do I use the LIKE wildcard in prepared statements for keyword-based searches in MySQL?

Mary-Kate Olsen
Release: 2024-11-17 15:38:01
Original
397 people have browsed it

How do I use the LIKE wildcard in prepared statements for keyword-based searches in MySQL?

Using "like" Wildcard in Prepared Statement

When implementing search functionality based on a keyword using prepared statements in SQL, it's necessary to utilize the LIKE keyword. However, understanding how to incorporate it into the prepared statement can be confusing.

To specify the keyword text in the prepared statement, it's crucial to set it within the value itself, not in the SQL string of the prepared statement. As such, the proper way to implement a prefix-match LIKE search would be as follows:

notes = notes
    .replace("!", "!!")
    .replace("%", "!%")
    .replace("_", "!_")
    .replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
        "SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");
Copy after login

Alternatively, suffix-match and global match variants can be implemented using similar techniques:

// Suffix match
pstmt.setString(1, "%" + notes);

// Global match
pstmt.setString(1, "%" + notes + "%");
Copy after login

By using these techniques, one can effectively utilize the LIKE keyword within prepared statements to perform keyword-based searches in MySQL queries.

The above is the detailed content of How do I use the LIKE wildcard in prepared statements for keyword-based searches in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template