I have requirement in Java to fire a query on MS SQL like
select * from customer
where customer.name in ('abc', 'xyz', ...,'pqr');
But I have this IN clause values in the form of ArrayList of String. For ex: the list look like {"abc","xyz",...,"pqr"}
I created a Prepared Statement :
PreparedStatement pStmt = conn.prepareStatement(select * from customer
where customer.name in (?));
String list= StringUtils.join(namesList, ",");
pStmt.setString(1,list);
rs = pStmt.executeQuery();
But the list is like "abc,xyz,..,pqr", but I want it as "'abc','xyz',..,'pqr'" so that I can pass it to Prepares Statement.
How to do it in JAva with out GUAVA helper libraries.
Thanks in Advance!!
We can convert ArrayList to a comma-separated String using StringJoiner which is a class in java. util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
You'll need to use opposite quotation marks inside and outside of JavaScript single or double quotes. That means strings containing single quotes need to use double quotes and strings containing double quotes need to use single quotes.
Approach: This can be achieved with the help of join() method of String as follows. Get the Set of String. Form a comma separated String from the Set of String using join() method by passing comma ', ' and the set as parameters. Print the String.
String str1 = "This is Jack's mobile"; String str2 = "\"This is it\"!"; Above, for single quote, we have to mention it normally like. However, for double quotes, use the following and add a slash in the beginning as well as at the end.
List<String> nameList = ...
String result = nameList.stream().collect(Collectors.joining("','", "'", "'"));
For converting the string you can try this:
String list= StringUtils.join(namesList, "','");
list = "'" + list + "'";
But i dont thing it's a good idea to pass one string for multiple params.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With