关于sql中的转义字符,记录一下:
实验环境: mySql
where xxx = '检索条件' -> 默认特殊字符: ' \ (单引号,反斜杠)
where xxx like '检索条件' -> 默认特殊字符: ' \ _ % (单引号,反斜杠,下划线,百分号)
对应上述问题,可以在java端进行转义
public static String escapeDataBaseByEqual(String key) {
if(CommonUtil.isNullString(key)) {
return key;
}
return key.replace("\\","\\\\").replace("'", "''");
}
public static String escapeDataBaseByLike(String key) {
if(CommonUtil.isNullString(key)) {
return key;
}
return key.replace("\\", "\\\\\\\\").replace("%", "\\%").replace("%", "\\%")
.replace("_", "\\_").replace("_", "\\_").replace("'", "''");
}
另外说一下 like语句,与等于号两种匹配方式中,存在反斜杠时,单个反斜杠分别替换成4个和2个