PreparedStatement IN clause alternatives?

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

    There are different alternative approaches that we can use for IN clause in PreparedStatement.

    1. Using Single Queries - slowest performance and resource intensive
    2. Using StoredProcedure - Fastest but database specific
    3. Creating dynamic query for PreparedStatement - Good Performance but doesn't get benefit of caching and PreparedStatement is recompiled every time.
    4. Use NULL in PreparedStatement queries - Optimal performance, works great when you know the limit of IN clause arguments. If there is no limit, then you can execute queries in batch. Sample code snippet is;

          int i = 1;
          for(; i <=ids.length; i++){
              ps.setInt(i, ids[i-1]);
          }
      
          //set null for remaining ones
          for(; i<=PARAM_SIZE;i++){
              ps.setNull(i, java.sql.Types.INTEGER);
          }
      

    You can check more details about these alternative approaches here.

提交回复
热议问题