1

我有一个字符串,其中包含用逗号分隔的值。现在根据我的需要,我必须用逗号 (,) 拆分字符串并将子字符串连接成查询字符串,但我无法理解..这是我的代码。 ..我需要拆分字符串并连接到查询中..

扩展包含像 1111,2341,5028 这样的值

String extension = request.getParameter("extension");
System.out.println(extension);
if(extension!=""){
//here i need to concate the substring into query delimited by comma.
query=query.concat("'").concat(" and extension='"+extension);

}

任何帮助将不胜感激..提前致谢..

4

4 回答 4

1

您可以使用拆分方法并一一获取子字符串

for (String ext: extension.split(",")){
   // your code goes here
  }
于 2013-10-21T11:13:30.920 回答
1

尝试这个,

{
        String myInput = "1111,2341,5028";
        String[] splitted = myInput.split(",");

        String query = " Select * from Table where "; // something like Select * from Table where 
        StringBuilder concanatedquery= new StringBuilder();

        for (String output : splitted) 
        {
            concanatedquery.append(" extension = '" + output.replace("'", "''") +"'  AND ");    //replace confirms that no failure will be there if splited string contains ' and if this splitted string are numeric then remove 'replace' clause and char ' after extension = ' and before "' AND"            
        }

        query = query + concanatedquery.substring(0, concanatedquery.length() - 4); //4 characters are removed as 'AND  ' will be extra at the end.
}
于 2013-10-21T11:23:53.567 回答
0

使用 StringBuilder 类连接和构建具有 append 方法的 SQL 查询。

String [] parts = originalString.split(",");
StringBuilder builder = new StringBuilder();
for(String str: parts){
 builder.append(str);
builder.append(" ");
}
return builder.toString();
于 2013-10-21T11:12:46.873 回答
0

You could Split the string Like this

String str = "1111,2341,5028";
String filenameArray[] =  str.split("\\,");
// ACCESS THE ARRAY POSITION LIKE filenameArray[0],filenameArray[1]  AND SO ON 
于 2013-10-21T11:16:03.493 回答