0

I have the below list

ArrayList<String> list1=new ArrayList<String>();
list1.add("abc");
list1.add("bdc");
list1.add("acr");
list1.add("bde");

I wanted to use this list in a select query like below

select * from emp where emp_name in ('abc','bdc','acr','bde')

I am using spring boot rest template and tried with ArrayList paramsList =new ArrayList() but it failed. Is there a easy way to do instead of converting into a string by iteration.

user14963721
  • 1
  • 1
  • 1
  • ***Warning:*** Code is susceptible to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks, and SQL syntax errors. Do not build SQL using string concatenation with text values of indeterminate origin. Use a `PrepareStatement` and parameter markers. – Andreas Jan 08 '21 at 06:05

1 Answers1

-1

You can join the strings in the list to get what you want:

String values = list1.stream().map(str -> String.format("'%s'", str)).collect(Collectors.joining(","));

And build the query like:

"select * from emp where emp_name in ("+ values +")";

However, as pointed out by @Andreas this approach is susceptible to SQL Injection attacks and syntax errors (if the values in the list have SQL reserved keywords or special characters). Therefore, you should be using prepared statements instead of concatenating strings like this.

Imesha Sudasingha
  • 3,462
  • 1
  • 23
  • 34