我建议你使用 StringBuilder。它们为您的字符串操作类型提供了一些性能提升,尤其是当您的 sql 或参数是长字符串时。
这是一个例子:
String param = "aa,bb,cc";
String str =
"select column_val from table_name where a = '?' and b = '?' and c = '?'";
@Test
public void Substitute(){
StringBuilder builder=new StringBuilder(str);
String[] params = param.split(",");
int position=0;
for (String paramValue:params){
position=builder.indexOf("?",position);
if (position==-1)
throw new RuntimeException("too parameter values specified.");
builder.replace(position,position+1,paramValue);
position++;
}
position=str.indexOf("?",position);
if (position!=-1)
throw new RuntimeException("Not all parameter specified.");
Assert.assertEquals(builder.toString(),
"select column_val from table_name where a = 'aa' and b = 'bb' and c = 'cc'");
}
正如其他人所说,请记住清理参数值以避免安全问题......