creating comma seperated string to be given as input to sql "IN" clause
I want a string开发者_Python百科 to be given as input to the SQL "IN" clause,where in i want a list of strings separated by commas
You can use guava's Joiner
:
Joiner.on(",").join(inputsList);
This does the job:
public String separateByComma(List<String> input) {
// check for valid input!!
public StringBuilder sb = new StringBuilder(input.get(0));
for (int i = 1; i < input.size(); i++)
sb.append(",").append(input.get(i));
return sb.toString();
}
BTW - you may need the Strings boxed in double quotes:
public String separateByCommaForSQL(List<String> input) {
// check for valid input!!
public StringBuilder sb = new StringBuilder("\""+input.get(0)+ "\"");
for (int i = 1; i < input.size(); i++)
sb.append(",\"").append(input.get(i)).append("\"");
return sb.toString();
}
You should use a PreparedStatement so your strings are escaped automatically if necessary and you will be protected from sql injection.
First, generate a statement with a marker for each element in the list. For example:
select id, name from users where name in (?, ?, ?)
Then loop over your list and set the values in the statement.
Take a look at this question for details:
What is the best approach using JDBC for parameterizing an IN clause?
You may use org.apache.commons.lang.StringUtils.join() method, or implement join operation yourself.
As pointed out by the other answers, there are many helpers you can use to do the joining.
I'd like to add a caveat:
Be aware that most DBMS have a upper limit on the number of values that you can concatenate like this. We have run into this before; if you are not certain that you will never have more than a few dozen values or so, you must make sure you do not exceed this limit (which is different for every DBMS, sometimes even configurable).
The limit usually comes either from a limit on the total size of an SQL statement, or an explicit limit on the number of values in a comma-separated list.
If you run into this problem, an alternative is to create a temporary (or permanent) table for the values list, and INSERT
your values into this table. Then you can use a WHERE xxx IN (SELECT column FROM helpertable)
instead of putting the list into the SQL statement. This avoids the maximum length problem; it is also probably faster if you need to re-use the list. It' more hassle (and probably slower) if you only need the list once though...
An unusual solution: If the Strings are in ArrayList
or LinkedList
(sub class of java.util.AbstractCollection
), call toString()
which returns "[e1, e2, e3...]". Then you could handle the string.
精彩评论