list集合对象怎么用stringbuffer拼接sql
时间: 2023-12-27 20:01:53 浏览: 73
语句?
你可以使用Java 8的Stream流来处理List集合对象,并使用StringJoiner类或StringBuffer类来拼接SQL语句。下面是一个示例代码:
List<String> list = Arrays.asList("apple", "banana", "orange");
StringJoiner joiner = new StringJoiner(",");
list.forEach(joiner::add);
String sql = "SELECT * FROM fruits WHERE name IN (" + joiner.toString() + ")";
或者你也可以使用StringBuffer类来拼接SQL语句:
List<String> list = Arrays.asList("apple", "banana", "orange");
StringBuffer buffer = new StringBuffer();
buffer.append("SELECT * FROM fruits WHERE name IN (");
for (int i = 0; i < list.size(); i++) {
buffer.append("'");
buffer.append(list.get(i));
buffer.append("'");
if (i < list.size() - 1) {
buffer.append(",");
}
}
buffer.append(")");
这样就可以将List集合对象中的元素用逗号分隔拼接成SQL语句中的IN条件了。
阅读全文