I need to do select * based on a list of input ids, what’s the best way of batch select? here’s what I have
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
}
It looks pretty fine to me. Just spotted a logical bug there in this block of code,
It will not append a
,after the first element. And there would be a,after the last. So, you need not care about that,here. Just do it this wayThen chop last two characters like this,