数据库sql查询支持上下文变量
This commit is contained in:
@@ -5,6 +5,8 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* @author liangdaliang
|
||||
@@ -66,6 +68,32 @@ public class MySQLExecutor {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String replaceSqlVariables(String sql, Map<String, String> params) {
|
||||
if (sql == null || params == null) {
|
||||
return sql;
|
||||
}
|
||||
// 正则匹配 ${variable_name}
|
||||
Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}");
|
||||
Matcher matcher = pattern.matcher(sql);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
while (matcher.find()) {
|
||||
String key = matcher.group(1).trim(); // 获取变量名
|
||||
String replacement = params.get(key); // 从 map 中获取对应值
|
||||
|
||||
if (replacement != null) {
|
||||
// 如果值存在,替换并加上单引号(适用于字符串)
|
||||
// 如果你需要支持数字不加引号,请自行判断类型
|
||||
replacement = "'" + replacement.replace("'", "''") + "'";
|
||||
matcher.appendReplacement(sb, replacement);
|
||||
}
|
||||
}
|
||||
|
||||
matcher.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
// public static void main(String[] args) {
|
||||
// String url = "jdbc:mysql://47.103.142.5:3306/cmcf-test";
|
||||
// List<String> columnNameList = new ArrayList<>();
|
||||
|
||||
Reference in New Issue
Block a user