PreparedStatement IN clause alternatives?

前端 未结 30 3882
情歌与酒
情歌与酒 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:49

    PreparedStatement doesn't provide any good way to deal with SQL IN clause. Per http://www.javaranch.com/journal/200510/Journal200510.jsp#a2 "You can't substitute things that are meant to become part of the SQL statement. This is necessary because if the SQL itself can change, the driver can't precompile the statement. It also has the nice side effect of preventing SQL injection attacks." I ended up using following approach:

    String query = "SELECT my_column FROM my_table where search_column IN ($searchColumns)";
    query = query.replace("$searchColumns", "'A', 'B', 'C'");
    Statement stmt = connection.createStatement();
    boolean hasResults = stmt.execute(query);
    do {
        if (hasResults)
            return stmt.getResultSet();
    
        hasResults = stmt.getMoreResults();
    
    } while (hasResults || stmt.getUpdateCount() != -1);
    

提交回复
热议问题