我同意你应该使用它PreparedStatement
来防止 SQL 注入。
但是,如果您决定在 String 中进行替换,则appendReplacement
可以正常工作:
final String in = "POLICY_NO = %POLNO% and A.POLICY_DETAILS_ID = b.POLICY_DETAILS_ID and b.ACTION_TIME = (select max(ACTION_TIME) from POLICY_DETAILS where POLICY_NO = %POLICYID%)";
// initialize map
final Map<String, String> map = new HashMap<String, String>();
map.put( "POLNO", "1234567" );
map.put( "POLICYID", "3" );
final Pattern pattern = Pattern.compile( "%.*?%" );
final Matcher matcher = pattern.matcher( in );
final StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
final String found = matcher.group();
final String withoutPercents = found.substring( 1, found.length() - 1 );
matcher.appendReplacement( sb, map.get( withoutPercents ) );
// instead of map.get(), there could be session.getAttribute( withoutPercents )
}
matcher.appendTail( sb );
System.out.println( sb.toString() );
UPD:根据下面的评论