user75ponic user75ponic - 1 year ago 66
Java Question

Pass String array values to sql IN condition

I have String array like

String[] val=request.getParameterValues("Names");
for(int i=0;i<val.length;i++){
//printval[i];
}


I would like to assign the values of String array to a sql statement as

How can I pass all the string values to sql condition? If array have the following values
JAMES,SMITH, JAKE
etc, then I would pass it as

sql = "where dept_name in('JAMES','SMITH','JAKE')";


Ideally I would want the string array values to be passed inside the in condition of sql.

Answer Source

You can construct a query as a filter and append this query to your main query.

StringBuilder sb= new StringBuilder();
String filter = "";

String[] val=request.getParameterValues("Names");  
for(int i=0;i<val.length;i++){  
 //printval[i];
 sb.append( "'"+val[i]+"'," );
}

filter = sb.ToString();
filter = filter.substring(0, filter.length()-1);

sql =  "where dept_name in("+filter+")"; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download