PreparedStatement IN clause alternatives?

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

    No simple way AFAIK. If the target is to keep statement cache ratio high (i.e to not create a statement per every parameter count), you may do the following:

    1. create a statement with a few (e.g. 10) parameters:

      ... WHERE A IN (?,?,?,?,?,?,?,?,?,?) ...

    2. Bind all actuall parameters

      setString(1,"foo"); setString(2,"bar");

    3. Bind the rest as NULL

      setNull(3,Types.VARCHAR) ... setNull(10,Types.VARCHAR)

    NULL never matches anything, so it gets optimized out by the SQL plan builder.

    The logic is easy to automate when you pass a List into a DAO function:

    while( i < param.size() ) {
      ps.setString(i+1,param.get(i));
      i++;
    }
    
    while( i < MAX_PARAMS ) {
      ps.setNull(i+1,Types.VARCHAR);
      i++;
    }
    

提交回复
热议问题