MankitaP
MankitaP

Reputation: 67

not passing List of String as single parameters inside preparedStatement.setObject()

I want to pass a List of String coming from request parameter to the preparedStatement.setObject() as a single parameter.Here I have coverted list of Objects to a single String.

So while passing this converted String to setObject method it is converting ' to \'.

So my query is like :

select * from category where category IN (?)

  for (int counter = 0; (!sqlParams.isEmpty()) && counter < sqlParams.size(); counter++) {
     System.out.println(sqlParams.get(counter)); 
     stmt.setObject(counter + 1, sqlParams.get(counter));
     System.out.println(stmt.toString());
}

here sqlParams.get(counter) is giving following value to me.

'Adult', 'Classic', 'Fantasy', 'Mystery'

but wen i am using stmt.setObject(), and printing the values of stmt, it is showing following value :

'\'Adult\', \'Classic\', \'Fantasy\', \'Mystery\''

So at query formation is something like this :

SELECT * FROM mytable WHERE category IN ('Adult\', \'Classic\', \'Fantasy\', \'Mistry\'');

There are other ways to solve these approach too, such as passing individual String and then query execution for each individual String.but It will increase time complexity for my code. Can anyone Suggest me the solution for this?

Upvotes: 0

Views: 604

Answers (1)

Joni
Joni

Reputation: 111349

JDBC prepared statements cannot be used when the number of parameters is variable, like here. The ? in the query is expanded into a single value, not to several separated by commas.

What you can do is construct an sql with the appropriate number of ?s and then set each parameter in a loop.

Upvotes: 3

Related Questions