4

I have a array list of integers . I want to use this list in the IN clause of SQL query. I tried to do the below, but i know it wont work. Can someone suggest a better way .

List<Integer> **plcList**  = new ArrayList<Integer>();
String finalQuery = "
select plc,direction,ROUND(AVG(CAST(speed as float)),2) as speed,COUNT(plc) as count,time_id 
from processed 
WHERE plc IN " + " " + "(**plcList**)"+ " " + "
group by plc, direction, time_id";
jmail
  • 5,944
  • 3
  • 21
  • 35
Shashank S
  • 161
  • 4
  • 18

3 Answers3

0

I am not a Java prof. but I would suggest you to loop throug your list and make string with comma seperated values. Like in PHP we do this with implode function. And hence your final string would be something like this

 1,2,3,4,5

and then use it in your sql query

I am not sure about my code but try this as I am not a Java programmar ( make the necessary changes if any syntax error)

String intlist = "";
for (String temp : list) 
{
   intlist += ","+temp;
}
String Str = new String(intlist);
String sqlstring = Str.substring(1);
Airy
  • 5,484
  • 7
  • 53
  • 78
  • Does not matter Abdul. Any help is greatly appreciated. Anyways, I was able to crack what I wanted to do :) – Shashank S Apr 04 '14 at 09:40
0

I suggest to have a look on this one: PreparedStatement IN clause alternatives?

And this page: http://www.javaranch.com/journal/200510/Journal200510.jsp#a2

In your case, you could just loop to build the integer list as Abdul mentioned above.

Community
  • 1
  • 1
GBO
  • 1
  • 1
  • I just figured out how to achieve it. It's pretty simple .String plcCSV = plcList.toString().replace("[", "'").replace("]", "'"); – Shashank S Apr 04 '14 at 09:39
0

Try this..

List<Integer> myList = new ArrayList<Integer>();
StringBuilder builder = new StringBuilder();
// length of the list
int locSize = myList.size();

Object[] args = new Object[locSize];               
for( int i = 0; i < locSize; i++ ) {
  builder.append(" ?, " );
  args[i]= myList.get(i);
}

You can then use this in your query, something like this.

....WHERE plc IN ("+ builder.toString() +") group by plc, direction, time_id";

Refer passing object[] to sql query for similar question.

Community
  • 1
  • 1
CuE
  • 361
  • 3
  • 9
  • I just figured out how to achieve it. It's pretty simple .String plcCSV = plcList.toString().replace("[", "'").replace("]", "'"); – – Shashank S Apr 09 '14 at 11:27