2012-05-30 5 views
-2

Java의 기존 문자열에서 특정 문자열을 어떻게 대체 할 수 있습니까?문자열의 특정 색인에서 문자열 바꾸기?

예 :

지금 내가 좋아하는 그 위치에 PARAMS을 대체 할
String param = "aa,bb,cc"; 
String str = 
    "select column_val from table_name where a = '?' and b = '?' and c = '?'"; 

..

String newStr = 
    "select column_val from table_name where a = 'aa' and b = 'bb' and c = 'cc'"; 

우리가 어떻게 할 수 있습니까? stringutil에 기존 메서드가 있습니까? 아니면이 메서드를 사용할 수 있습니까?

+3

당신이 준비된 명령문 대신 편집 쿼리를 사용하는 것으로 간주합니까? – triclosan

답변

0

StringBuilder를 사용하는 것이 좋습니다. 그들은 문자열 조작의 유형에서 성능 향상을 제공합니다. 특히 SQL 또는 params가 긴 문자열 인 경우 더욱 그렇습니다. 여기

은 예입니다

다른 사람이 보안 문제를 방지하기 위해 PARAM 값을 소독하는 것을 잊지 말했듯이
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'"); 

} 

...

0

String.format는 사용하는 것과 같은 소리입니다. 기본적으로 C의 sprintf과 같습니다. 자세한 내용은 Formatter javadoc에서 확인할 수 있습니다.

6

이 문제를 해결하는 올바른 방법은 usingPreparedStatement입니다. 그것은 당신을 대신 할뿐만 아니라 SQL injection attacks으로부터 당신을 보호 할 것입니다.

String param = "aa,bb,cc"; 
String str = "select column_val from table_name where a = '?' and b = '?' and c = '?'"; 
String fmt = str.replaceAll("[?]", "%s"); 
String newStr = String.format(fmt, (Object[])param.split(",")); 

:

그래 난 그냥 여기 선택 쿼리를 보여하지만 쿼리를 선택하지 그, 그것은 이러한 경우 간단한 문자열

입니다, 그것을 할 수있는 쉬운 방법이있다 이것으로 입력하는 패턴에 물음표 나 퍼센트 문자가 있는지 확인하십시오.

+0

예제가 없다. 여기서 준비된 문을 사용할 수 없다. – Sanju

+0

문안을 준비하지 않은 이유는 무엇입니까? – sgowd

+0

@ sans481 - 일반적으로 문자열의 숯/문자열 대체를 보여주고 싶을 수도 있습니다. SQL 문자열이 우발적 일 수 있습니다! –

0
String param = "aa,bb,cc"; 
    String str = 
     "select column_val from table_name where a = # and b = # and c = #"; 
    String [] arr = param.split(","); 
    for(int i=0; i<arr.length; i++){str.indexOf("#"); 
     str = str.replaceFirst("#", "'"+arr[i]+"'"); 
    } 
    System.out.println(str); 
관련 문제