MySQL sql模糊查询-like特殊字符处理('、%、_、\) 作者:马育民 • 2022-04-25 08:51 • 阅读:10969 # 说明 SQL的 `LIKE` 模糊查询语句中,有一些特殊的字符,需要转换后才能搜索到结果: - `'`:用于包裹搜索条件,需转为 `\'` - `%`:用于代替任意数目的任意字符,需转换为 `\%` - `_`:用于代替一个任意字符,需转换为 `\_` - `\`:转义符号,分两种情况: - `\` 前面是 `%` 的,需要转换为 `\\\\\\` - `\` 前面不是 `%` 的,需要转换为 `\\\\` # 例子 ``` select * from article where title like '%\'%' ``` ``` select * from article where title like '%\%%' ``` ``` select * from article where title like '%\_%' ``` ``` select * from article where title like '%\\\\\\%' -- \前面是%的,需要6个\ ``` ``` select * from article where title like '%python \\\\%' -- \前面不是%的,需要4个\ ``` ### java 代码替换 ``` title2 = title2.replace("'","\'"); title2 = title2.replace("\\","\\\\\\"); title2 = title2.replace("%","\\%"); title2 = title2.replace("_","\\_"); ``` 原文出处:http://malaoshi.top/show_1IX3C7mPZprK.html