2017-04-27 80 views
0

我有以下java代碼,其中的字符串數組,即在運行時已知動態值的列表。我需要將此值傳遞給字符串變量中提到的查詢,即SQL。如何傳遞值('運行時已知'多少')到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()); 

一種方法是在循環中附上以下查詢,這會使查詢多次執行,從而影響性能。

其中i = 1,2,3,4 ... n。歡迎所有的答案,並提前謝謝你:)。

PS:在現實中,查詢僅僅是爲了問題的角度而設想的,相信我這是非常複雜和龐大的。

回答

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

非常有用TNX :) – Shashank

+0

有些數據庫有對「中的」設置大小限制。例如。在Oracle中,您可以傳遞1000個值。 – wumpz

+0

@wumpz是啊你是正確的,這是我使用下面的查詢使用'或'的原因。 (「+ list [1] +」)「OR 」col_1 IN(「+ list [2] +」)「.......或」col_1 IN( 「+列表[N] +」)「; – Shashank

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

非常有幫助tnx :) – Shashank