简体   繁体   中英

Converting List to a String in java for Oracle SQL IN clause

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM