2011-06-09 28 views
2

我需要做select *基于输入ID列表,什么是批次选择的最佳方式?这里是我所拥有的建筑物选择查询使用IN(...)条款

 
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 
} 

回答

2

对我来说这看起来相当不错。只要发现有一个逻辑错误在这个代码块,

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) + ')'); 
+0

这是可能的最快的方法? – user775187 2011-06-09 03:53:56

+0

@ user775187:如果'id'是唯一的,并且您需要基于多个'ids'查询记录 - 只要没有其他选项,那么'IN(...)'就是方法。因此,您必须使用此类或类似技术来构建您的查询。 – 2011-06-09 04:09:11