gpt4 book ai didi

java - 使用 IN(...) 子句构建选择查询

转载 作者:行者123 更新时间:2023-11-29 02:35:12 25 4
gpt4 key购买 nike

我需要根据输入 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com