我有以下java代码,其中字符串数组,即列表,它是运行时已知的动态值。我需要将这个值传递给string变量(即SQL )中提到的查询。
List[] list = new Arraylist();
String SQL = "select * from Table_name where col_1 IN ("+list[1]+")" OR
"col_1 IN("+list[2]+")" ....... OR "col_1 IN("+list[n]+")";
List <Class_Name> systemtails = jdbcTemplateObject.query(SQL, new
Class_Name_Mapper());一种方法是将后续查询封装在一个循环中,这使得查询不止一次地执行,哪一个循环会影响性能。
String SQL = "select * from Table_name where col_1 IN ("+list[i]+")";在哪里i=1,2,3,4...n。欢迎所有答复,并预先感谢:)。
PS :查询只是为了问题的角度,在现实中,相信我,它是非常复杂和庞大的。
发布于 2017-04-27 12:25:06
因此,我了解您的查询处于如下for循环中:
For int I = 0; I < list.size; I++ {
String SQL = "select * from Table_name where col_1 IN ("+list[i]+")";
List <Class_Name> systemtails = jdbcTemplateObject.query(SQL, new
Class_Name_Mapper());
}为什么不这样做呢?
String SQL = "select * from Table_name where col_1 IN (";
For int I = 0; I < list.size; I++ {
SQL+=list[I];
If(I != list.size -1){
SQL+=",";
}else{
SQL +=")";
}
}
List <Class_Name> systemtails = jdbcTemplateObject.query(SQL, new
Class_Name_Mapper());发布于 2017-04-27 12:25:31
首先,您应该使用PreparedStatement来避免使用SQL注入。
为此,我将使用for循环来构建IN条件。
boolean first = true;
String inCondition = "(";
for(int i = 0; i < list.length; i++){
if(first){
first = false;
} else {
inCondition += ", ";
}
inCondition += ?;
}
inCondition += ")";
PreparedStatement ps = "select * from Table_name where col_1 IN " + inCondition;
int index = 1;
for(String val : list) {
ps.setString(index++, val);
}https://stackoverflow.com/questions/43657556
复制相似问题