如何将值(“运行时已知多少”)传递给SQL查询

时间:2017-04-27 12:15:58

标签: java mysql arrays list arraylist

我有以下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:查询只是为了解决问题,现实中相信我非常复杂和大。

2 个答案:

答案 0 :(得分:1)

首先,您应该使用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);
}

答案 1 :(得分:0)

所以我理解你的查询是这样的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());