我正在尝试获取他们的id
在特定集合中的记录列表。我将通过Web服务从另一个应用程序获取此集。我应该写这样的查询:SELECT * FROM tbl_data WHERE id IN (?, ?, ?, ?)
。但问题是(?, ?, ?, ?)
部分是可变长度。对于一个请求,它就像:SELECT * FROM tbl_data WHERE id IN (?, ?, ?)
,而另一个请求就像:SELECT * FROM tbl_data WHERE id IN (?, ?, ?, ?, ?, ?)
。我真的不喜欢循环并逐个获取记录。有没有办法构建这个查询?
答案 0 :(得分:3)
您可以在代码中生成IN
部分查询。如果您知道应该是什么而不是? symbol
,那么您只需运行循环并构建它。
String sqlPart = "(";
for (every symbol but last){
sqlPart += symbol;
sqlPart += ",";
}
sqlPart += lastSymbol;
sqlPart += ")";
String sql = "SELECT * FROM tbl_data WHERE id IN " + sqlPart;
答案 1 :(得分:2)
您可以改为循环并构造字符串"?, ?, ? ... , ?"
,只需将问号添加为您需要向DB请求的ID。使用StringBuilder构造String
这里有一些示例代码:
@Test
public void genSqlInParameterString() {
String select = "SELECT * FROM my_table WHERE ";
System.out.println(select + genSqlInParameterString(null));
System.out.println(select + genSqlInParameterString(new String[]{}));
System.out.println(select + genSqlInParameterString(new String[]{"A"}));
System.out.println(select + genSqlInParameterString(new String[]{"A", "B"}));
}
public String genSqlInParameterString(String[] args) {
StringBuilder sb = new StringBuilder();
if(args != null && args.length > 0) {
sb.append("IN (");
for(int i = 0; i < args.length ; i++) {
sb.append('\'').append(args[i]).append('\'');
if(i < args.length-1) {
sb.append(", ");
}
}
sb.append(")");
}
if(sb.length() == 0) {
// condition evaluates to false, so that select returns nothing
// you may instead return 1=1 so that all records are returned
// handling no-paramters case depends on your requirements
sb.append("1=0");
}
return sb.toString();
}
<强>输出强>
SELECT * FROM my_table WHERE 1=0
SELECT * FROM my_table WHERE 1=0
SELECT * FROM my_table WHERE IN ('A')
SELECT * FROM my_table WHERE IN ('A', 'B')
答案 2 :(得分:2)
使用QueryDSL或JOOQ而不是手动编写SQL代码。