PreparedStatement IN clause alternatives?

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

    After examining various solutions in different forums and not finding a good solution, I feel the below hack I came up with, is the easiest to follow and code:

    Example: Suppose you have multiple parameters to pass in the 'IN' clause. Just put a dummy String inside the 'IN' clause, say, "PARAM" do denote the list of parameters that will be coming in the place of this dummy String.

        select * from TABLE_A where ATTR IN (PARAM);
    

    You can collect all the parameters into a single String variable in your Java code. This can be done as follows:

        String param1 = "X";
        String param2 = "Y";
        String param1 = param1.append(",").append(param2);
    

    You can append all your parameters separated by commas into a single String variable, 'param1', in our case.

    After collecting all the parameters into a single String you can just replace the dummy text in your query, i.e., "PARAM" in this case, with the parameter String, i.e., param1. Here is what you need to do:

        String query = query.replaceFirst("PARAM",param1); where we have the value of query as 
    
        query = "select * from TABLE_A where ATTR IN (PARAM)";
    

    You can now execute your query using the executeQuery() method. Just make sure that you don't have the word "PARAM" in your query anywhere. You can use a combination of special characters and alphabets instead of the word "PARAM" in order to make sure that there is no possibility of such a word coming in the query. Hope you got the solution.

    Note: Though this is not a prepared query, it does the work that I wanted my code to do.

    0 讨论(0)
  • 2020-11-21 05:41

    Here's a complete solution in Java to create the prepared statement for you:

    /*usage:
    
    Util u = new Util(500); //500 items per bracket. 
    String sqlBefore  = "select * from myTable where (";
    List<Integer> values = new ArrayList<Integer>(Arrays.asList(1,2,4,5)); 
    string sqlAfter = ") and foo = 'bar'"; 
    
    PreparedStatement ps = u.prepareStatements(sqlBefore, values, sqlAfter, connection, "someId");
    */
    
    
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Util {
    
        private int numValuesInClause;
    
        public Util(int numValuesInClause) {
            super();
            this.numValuesInClause = numValuesInClause;
        }
    
        public int getNumValuesInClause() {
            return numValuesInClause;
        }
    
        public void setNumValuesInClause(int numValuesInClause) {
            this.numValuesInClause = numValuesInClause;
        }
    
        /** Split a given list into a list of lists for the given size of numValuesInClause*/
        public List<List<Integer>> splitList(
                List<Integer> values) {
    
    
            List<List<Integer>> newList = new ArrayList<List<Integer>>(); 
            while (values.size() > numValuesInClause) {
                List<Integer> sublist = values.subList(0,numValuesInClause);
                List<Integer> values2 = values.subList(numValuesInClause, values.size());   
                values = values2; 
    
                newList.add( sublist);
            }
            newList.add(values);
    
            return newList;
        }
    
        /**
         * Generates a series of split out in clause statements. 
         * @param sqlBefore ""select * from dual where ("
         * @param values [1,2,3,4,5,6,7,8,9,10]
         * @param "sqlAfter ) and id = 5"
         * @return "select * from dual where (id in (1,2,3) or id in (4,5,6) or id in (7,8,9) or id in (10)"
         */
        public String genInClauseSql(String sqlBefore, List<Integer> values,
                String sqlAfter, String identifier) 
        {
            List<List<Integer>> newLists = splitList(values);
            String stmt = sqlBefore;
    
            /* now generate the in clause for each list */
            int j = 0; /* keep track of list:newLists index */
            for (List<Integer> list : newLists) {
                stmt = stmt + identifier +" in (";
                StringBuilder innerBuilder = new StringBuilder();
    
                for (int i = 0; i < list.size(); i++) {
                    innerBuilder.append("?,");
                }
    
    
    
                String inClause = innerBuilder.deleteCharAt(
                        innerBuilder.length() - 1).toString();
    
                stmt = stmt + inClause;
                stmt = stmt + ")";
    
    
                if (++j < newLists.size()) {
                    stmt = stmt + " OR ";
                }
    
            }
    
            stmt = stmt + sqlAfter;
            return stmt;
        }
    
        /**
         * Method to convert your SQL and a list of ID into a safe prepared
         * statements
         * 
         * @throws SQLException
         */
        public PreparedStatement prepareStatements(String sqlBefore,
                ArrayList<Integer> values, String sqlAfter, Connection c, String identifier)
                throws SQLException {
    
            /* First split our potentially big list into lots of lists */
            String stmt = genInClauseSql(sqlBefore, values, sqlAfter, identifier);
            PreparedStatement ps = c.prepareStatement(stmt);
    
            int i = 1;
            for (int val : values)
            {
    
                ps.setInt(i++, val);
    
            }
            return ps;
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-21 05:41

    For some situations regexp might help. Here is an example I've checked on Oracle, and it works.

    select * from my_table where REGEXP_LIKE (search_column, 'value1|value2')
    

    But there is a number of drawbacks with it:

    1. Any column it applied should be converted to varchar/char, at least implicitly.
    2. Need to be careful with special characters.
    3. It can slow down performance - in my case IN version uses index and range scan, and REGEXP version do full scan.
    0 讨论(0)
  • 2020-11-21 05:42

    An unpleasant work-around, but certainly feasible is to use a nested query. Create a temporary table MYVALUES with a column in it. Insert your list of values into the MYVALUES table. Then execute

    select my_column from my_table where search_column in ( SELECT value FROM MYVALUES )
    

    Ugly, but a viable alternative if your list of values is very large.

    This technique has the added advantage of potentially better query plans from the optimizer (check a page for multiple values, tablescan only once instead once per value, etc) may save on overhead if your database doesn't cache prepared statements. Your "INSERTS" would need to be done in batch and the MYVALUES table may need to be tweaked to have minimal locking or other high-overhead protections.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • try using the instr function?

    select my_column from my_table where  instr(?, ','||search_column||',') > 0
    

    then

    ps.setString(1, ",A,B,C,"); 
    

    Admittedly this is a bit of a dirty hack, but it does reduce the opportunities for sql injection. Works in oracle anyway.

    0 讨论(0)
提交回复
热议问题