简体   繁体   中英

How to escape special characters from SQL LIKE clause?

I'm using the guide at https://www.baeldung.com/rest-api-search-language-rsql-fiql to build an RSQL based JPA specification.

The like clause looks like the following:

return builder.like(root.get(property), argument.toString().replace('*', '%'));

My question is, what is the best way to handle escaping special characters in the user's input?

For example, if the user supplied the string:

*my-search%-term*

the above code would translate this to:

%my-search%-term%

I would want to escape the % in the string so that it is not evaluated as the % wildcard in the LIKE clause.

The following post states the LIKE special characters for each database:

List of special characters for SQL LIKE clause

and also note this comment from one of the answers:

It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)

I am wondering what the best way to handle this is? I'm using postgres in production, and h2 in testing, but ideally don't want the solution tied to either of these.

Why not use regular expression matching instead of like ?

where col ~ <user input>

It sounds like your users may be more familiar with regular expressions.

If you just want an exact match that ignores all wildcard functionality, you can use position:

where position(<user input> in col) > 0

In standard SQL you only need to escape the % and _ characters as those are the only wildcards supported by the LIKE operator.

So *my-search%-term* should be used like this in SQL

WHERE some_column LIKE '%my-search\%-term%' escape '\'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM