PreparedStatement IN clause alternatives?

前端 未结 30 3997
情歌与酒
情歌与酒 2020-11-21 05:19

What are the best workarounds for using a SQL IN clause with instances of java.sql.PreparedStatement, which is not supported for multiple values du

30条回答
  •  故里飘歌
    2020-11-21 05:27

    SetArray is the best solution but its not available for many older drivers. The following workaround can be used in java8

    String baseQuery ="SELECT my_column FROM my_table where search_column IN (%s)"
    
    String markersString = inputArray.stream().map(e -> "?").collect(joining(","));
    String sqlQuery = String.format(baseSQL, markersString);
    
    //Now create Prepared Statement and use loop to Set entries
    int index=1;
    
    for (String input : inputArray) {
         preparedStatement.setString(index++, input);
    }
    

    This solution is better than other ugly while loop solutions where the query string is built by manual iterations

提交回复
热议问题