PreparedStatement IN clause alternatives?

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

    Here's how I solved it in my own application. Ideally, you should use a StringBuilder instead of using + for Strings.

        String inParenthesis = "(?";
        for(int i = 1;i < myList.size();i++) {
          inParenthesis += ", ?";
        }
        inParenthesis += ")";
    
        try(PreparedStatement statement = SQLite.connection.prepareStatement(
            String.format("UPDATE table SET value='WINNER' WHERE startTime=? AND name=? AND traderIdx=? AND someValue IN %s", inParenthesis))) {
          int x = 1;
          statement.setLong(x++, race.startTime);
          statement.setString(x++, race.name);
          statement.setInt(x++, traderIdx);
    
          for(String str : race.betFair.winners) {
            statement.setString(x++, str);
          }
    
          int effected = statement.executeUpdate();
        }
    

    Using a variable like x above instead of concrete numbers helps a lot if you decide to change the query at a later time.

提交回复
热议问题