作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要根据输入 ID 列表进行选择 *,批量选择的最佳方式是什么?这是我的
StringBuilder inClause = new StringBuilder();boolean firstValue = true;for (int i=0; i < batchSize; i++) { inClause.append('?'); if ( firstValue ) { firstValue = false; } else { inClause.append(','); }}PreparedStatement stmt = conn.prepareStatement( "select id, name from users where id in (" + inClause.toString() + ')');for (int i=0; i < batchSize; i++) { stmt.setInt(i); // or whatever values you are trying to query by}
最佳答案
我觉得还不错。刚刚在这段代码中发现了一个逻辑错误,
boolean firstValue = true;
for (int i=0; i < batchSize; i++) {
inClause.append('?');
if ( firstValue ) {
firstValue = false;
} else {
inClause.append(',');
}
}
它不会在第一个元素后附加 ,
。在最后一个之后会有一个,
。因此,您无需关心此处的 ,
。就这样做吧
for (int i=0; i < batchSize; i++) {
inClause.append('?, ');
}
然后像这样切掉最后两个字符,
PreparedStatement stmt = conn.prepareStatement(
"select id, name from users where id in (" +
inClause.substring(0, inClause.length()-2) + ')');
关于java - 使用 IN(...) 子句构建选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6287187/
我是一名优秀的程序员,十分优秀!