[英]How to convert a string of coma separated characters to a string of strings with each string in single quotes and separated by comma
[英]how to create comma separated string in single quotes from arraylist of string in JAVA
我需要在 Java 中触发对 MS SQL 的查询,例如
select * from customer
where customer.name in ('abc', 'xyz', ...,'pqr');
但是我有这个 IN 子句值的形式为 ArrayList of String。 例如:列表看起来像 {"abc","xyz",...,"pqr"}
我创建了一个准备好的声明:
PreparedStatement pStmt = conn.prepareStatement(select * from customer
where customer.name in (?));
String list= StringUtils.join(namesList, ",");
pStmt.setString(1,list);
rs = pStmt.executeQuery();
但是列表就像"abc,xyz,..,pqr" ,但我希望它是"'abc','xyz',..,'pqr'"以便我可以将它传递给 Prepares Statement。
如何在没有 GUAVA 帮助程序库的情况下在 JAva 中做到这一点。
提前致谢!!
我知道这是一个非常古老的帖子,但万一有人正在寻找如何以Java 8方式做到这一点:
private String join(List<String> namesList) {
return String.join(",", namesList
.stream()
.map(name -> ("'" + name + "'"))
.collect(Collectors.toList()));
}
要转换字符串,您可以尝试:
String list= StringUtils.join(namesList, "','");
list = "'" + list + "'";
但我不认为为多个参数传递一个字符串是个好主意。
即使你按照自己的意愿格式化了字符串,它也行不通。 您不能使用多个值替换PreparedStatement
一个占位符。
您应该动态构建PreparedStatement
以包含与输入列表中的元素一样多的占位符。
我会做这样的事情:
StringBuilder scmd = new StringBuilder ();
scmd.append ("select * from customer where customer.name in ( ");
for (int i = 0; i < namesList.size(); i++) {
if (i > 0)
scmd.append (',');
scmd.append ('?');
}
scmd.append (")");
PreparedStatement stmt = connection.prepareStatement(scmd.toString());
if (namesList.size() > 0) {
for (int i = 0; i < namesList.size(); i++) {
stmt.setString (i + 1, namesList.get(i));
}
}
rs = stmt.executeQuery();
List<String> nameList = ...
String result = nameList.stream().collect(Collectors.joining("','", "'", "'"));
您可以为此类活动使用简单的分隔符。 基本上你想要一个第一次评估为“”的对象,但在第一个请求返回定义的字符串后发生变化。
public class SimpleSeparator<T> {
private final String sepString;
boolean first = true;
public SimpleSeparator(final String sep) {
this.sepString = sep;
}
public String sep() {
// Return empty string first and then the separator on every subsequent invocation.
if (first) {
first = false;
return "";
}
return sepString;
}
public static void main(String[] args) {
SimpleSeparator sep = new SimpleSeparator("','");
System.out.print("[");
for ( int i = 0; i < 10; i++ ) {
System.out.print(sep.sep()+i);
}
System.out.print("]");
}
}
我想最简单的方法是使用这样的表达式语言:
String[] strings = {"a", "b", "c"};
String result = ("" + Arrays.asList(strings)).replaceAll("(^.|.$)", "\'").replace(", ", "\',\'" );
nameList = List.of("aaa", "bbb", "ccc")
.stream()
.map(name -> "'" + name + "'")
.collect(Collectors.joining(","));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.