PreparedStatement IN clause alternatives?

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

    Generate the query string in the PreparedStatement to have a number of ?'s matching the number of items in your list. Here's an example:

    public void myQuery(List items, int other) {
      ...
      String q4in = generateQsForIn(items.size());
      String sql = "select * from stuff where foo in ( " + q4in + " ) and bar = ?";
      PreparedStatement ps = connection.prepareStatement(sql);
      int i = 1;
      for (String item : items) {
        ps.setString(i++, item);
      }
      ps.setInt(i++, other);
      ResultSet rs = ps.executeQuery();
      ...
    }
    
    private String generateQsForIn(int numQs) {
        String items = "";
        for (int i = 0; i < numQs; i++) {
            if (i != 0) items += ", ";
            items += "?";
        }
        return items;
    }
    

提交回复
热议问题