Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create comma separated string in single quotes from arraylist of string in JAVA

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!!

like image 219
LoneWolf Avatar asked Jan 14 '15 11:01

LoneWolf


People also ask

How do you convert an ArrayList to a comma separated string in Java?

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.

How do I put single quotes in a single quote in a string?

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.

How do you add comma separated values in a string in Java?

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.

How do you add a single quote to a string in Java?

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.


2 Answers

List<String> nameList = ...    
String result = nameList.stream().collect(Collectors.joining("','", "'", "'"));
like image 173
Igorock Avatar answered Sep 21 '22 17:09

Igorock


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.

like image 24
Szarpul Avatar answered Sep 22 '22 17:09

Szarpul