1

I have an sqlQuery:

select * from products where product_type in :prodTypes
query.setParameter("prodTypes",getInClauseFromList(productTypes));

productTypes is a List<String>

public String getInClauseFromList(List list) {
    if(list != null && !list.isEmpty()) {
      String inClause = Arrays.toString(list.toArray());
      inClause = inClause.replace("[", "('").replace("]", "')");
      inClause = inClause.replace(", ", "','");
      return inClause;
    }
    return "('')";
  }

I get an error:

Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version for the right
syntax to use near ''(\'clothes\')')
4
  • It would be helpful for you and us if you could also show us what the actual text of the query is. Right now, I think we could only speculate about the exact syntax error. Commented Jul 29, 2015 at 9:46
  • I tried the show sql: I get select * from products where product_type in ? It's not helpful :( Commented Jul 29, 2015 at 9:48
  • I need to see the IN clause as plain text. There is some small problem, but we need to see this. Commented Jul 29, 2015 at 9:48
  • OK...but this is a bit like throwing out the baby with the bathwater. My advice to you is to print to console or log the result from getInClauseFromList(). It will be obvious why MySQL is barfing on it. Commented Jul 29, 2015 at 9:54

1 Answer 1

1

I would recommend using something like Spring's JDBCTemplate. Then you don't have to convert the list manually to a String.

In your example above the String you are passing in is quoted (as it should be) and hence the resulting SQL is not correct.

Given that I don't know which type "query" is: Try setting the list directly as the parameter. Most of the frameworks should support converting it properly for the IN clause.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.