62,614
社区成员
发帖
与我相关
我的任务
分享
// 去年and () or()这种
labelSql = labelSql.replaceAll("(and|or)\\s?\\(\\s*+\\)\\s", "");
package test;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TTeeest {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("aa", "123");
getRunnableSql("select * from T1 where 1=1 and a = :aa and (b=:bb or b =:cc) and e like :ee", map);
}
/**
*
* 用参数替换sql的特殊标记,如果标记对应的参数存在,则直接替换,如果不存在,要把对应的一段条件去掉,最后得出一个能用于查询的sql语句,返回能用于查询的sql语句。
*
* @param labelSql
* 带有标记的sql语句, 如select * from T1 where 1=1 and a = :aa and (b
* =:bb or b =:cc) and e like :ee
*
* @param param
* 参数集合,如aa= "111" , bb= "222", cc= "333",dd = "444"
*
* @return 能用于查询的sql,如select * from T1 where 1=1 and a = 111 and (b = 222 or
* b = 333)
*
*/
public static String getRunnableSql(String labelSql, Map<String, Object> param) {
String regex1 = "(or|and)?\\s?[\\(?\\w?\\s?]\\s?(=|like)?\\s?:\\w+";
String regex2 = "(?<=:)\\w+";
Pattern pattern1 = Pattern.compile(regex1);
Pattern pattern2 = Pattern.compile(regex2);
Matcher matcher = pattern1.matcher(labelSql);
// 匹配找出以下
// and a = :aa
// b=:bb
// or b =:cc
// and e like :ee
while (matcher.find()) {
// 用于aa bb这些
String paramXX = null;
// 提取到要替换的字符串
String paramReplace = matcher.group();
Matcher matcher2 = pattern2.matcher(paramReplace);
// 再找出:aa中的aa
if (matcher2.find()) {
paramXX = matcher2.group();
}
// 找出map中的参数
Object mapParam = param.get(paramXX);
// 判断是否为null,为null则删除
if (mapParam == null) {
labelSql = labelSql.replaceAll(paramReplace, " ");
} else {
// 替换
labelSql = labelSql.replaceAll(":" + paramXX, mapParam.toString());
}
}
System.out.println(labelSql);
return null;
}
}