-2

Javaの既存の文字列の特定の文字列をどのように置き換えることができますか?

例:

String param = "aa,bb,cc";
String str = 
  "select column_val from table_name where a = '?' and b = '?' and c = '?'";

今、私はparamsをその位置に置き換えたい..

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

どうすればこれを行うことができますか?stringutil に既存のメソッドはありますか、またはこれを行うメソッドはありますか?

4

4 に答える 4

6

これを処理する正しい方法は、を使用すること PreparedStatementです。それはあなたの代わりになるだけでなく、SQLインジェクション攻撃からあなたを守ります。

はい、ここではクエリの選択を示していますが、クエリの選択ではなく、単純な文字列です

このような場合、それを行う簡単な方法があります。

 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(","));

これにフィードするパターンに、疑問符やパーセント文字が含まれていないことを確認してください。

于 2012-05-30T07:31:56.700 に答える
0

String.formatあなたが使うべきもののように聞こえます。基本的にはCのようなものsprintfです。詳細はFormatterjavadocにあります。

于 2012-05-30T07:30:31.897 に答える
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);
于 2012-05-30T07:44:25.580 に答える
0

StringBuilder を使用することをお勧めします。特に sql または params が長い文字列の場合、文字列操作のタイプでパフォーマンスが向上します。

次に例を示します。

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'");

}

他の人が言ったように、セキュリティの問題を回避するために param 値をサニタイズすることを忘れないでください...

于 2012-05-30T07:57:15.757 に答える