Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA sql NOT IN list statement

Am trying to select record from database where record id NOT IN list.

take a look @ my problem below.

String Sqlids = "2,6,3,9"; // this is dynamic so the number of element is unknown

String str= "SELECT TOP 1 * FROM student WHERE ID NOT IN (2,6,3,9) ORDER BY NEWID()";
PreparedStatement stat = con.prepareStatement(str);
ResultSet rs = stat.executeQuery();

The above statement work FINE, but if i change it to

String Sqlids = "2,6,3,9";
String str= "SELECT TOP 1 * FROM student WHERE ID NOT IN (Sqlids) ORDER BY NEWID()";
PreparedStatement stat = con.prepareStatement(str);
ResultSet rs = stat.executeQuery();

//i also try this
String Sqlids = "2,6,3,9";
String str= "SELECT TOP 1 * FROM student WHERE ID NOT IN (?) ORDER BY NEWID()";
PreparedStatement stat = con.prepareStatement(str);
stat.setString(1,Sqlids );

ResultSet rs = stat.executeQuery();

THE ABOVE STATEMENT DOESN'T FILTER Since Sqlids is one string is seeing it as one parameter so it return repeated rows, is there an integer format for storing values like 2,6,3,9 ? since the Sqlids is from an arraylist called SqlidList i try somtin like this

Iterator iTr = SqlidList.iterator();
while(iTr.hasNext()){
    stat.setString(1,iTr.next().toString()+",");
}

but the setString(1,--) is not available since is in a while loop

like image 794
easyscript Avatar asked Oct 24 '12 10:10

easyscript


People also ask

How do I pass a SQL query to a list in Java?

With Java 8 you can use String. join(",", list) , however this solution is not appropriate for String parameters. This code had a security issue. Because the values are not escaped, you can have SQL injection.

Can we create list in SQL?

You can create lists of SQL Query or Fixed Data values . In the Data Model components pane, click List of Values and then click Create new List of Values. Enter a Name for the list and select a Type.

How do you use PreparedStatement in clause?

When you use the IN clause in prepared statement you can use bind variables for the parameters list (one for each) and set values for those later using the setter methods of the PreparedStatement interface and, after setting values to all the bind variables in the statement you can execute that particular statement ...

What is a list in Java?

This Java List Tutorial Explains How to Create, Initialize and Print Lists in Java. The tutorial also Explains List of Lists with Complete Code Example: This tutorial will introduce you to the data structure ‘list’ which is one of the basic structures in the Java Collection Interface. A list in Java is a sequence of elements according to an order.

What is the use of EXECUTE statement in Java?

execute (java.lang.String) Moves to this Statement object's next result, returns true if it is a ResultSet object, and implicitly closes any current ResultSet object (s) obtained with the method getResultSet . There are no more results when the following is true:

What are the characteristics of list in Java?

Some of the characteristics of the list in Java include: Lists can have duplicate elements. The list can also have ‘null’ elements. Lists support generics i.e. you can have generic lists. You can also have mixed objects (objects of different classes) in the same list.

What is singletonlist in Java 8?

The ‘singletonList’ method returns a list with a single element in it. The list is immutable. The following Java program demonstrates all the three methods of the Collections class discussed above. With the introduction of streams in Java 8, you can also construct a stream of data and collect them in a list.


2 Answers

Use Connection#createArrayOf after converting your ids to a String[]

String[] ids = {"2", "6", "3", "9"};

String str= "SELECT TOP 1 * FROM student WHERE ID NOT IN ? ORDER BY NEWID()";
PreparedStatement stat = con.prepareStatement(str);
stat.setArray(1, con.createArrayOf("text",ids));
ResultSet rs = stat.executeQuery();

If createArrayOf is not supported by your JDBC driver (as in this case) I'd probably just construct the query string in place e.g:

String Sqlids = "2,6,3,9";
String str= "SELECT TOP 1 * FROM student WHERE ID NOT IN ("+Sqlids+") ORDER BY NEWID()";

or if you have a collection of ids use a utility method to create the array content:

public static String toSqlArray(List<String> strings) {
    StringBuilder sb = new StringBuilder();
    boolean doneOne = false;
    for(String str: strings){
        if(doneOne){
            sb.append(", ");
        }
        sb.append("'").append(str).append("'");
        doneOne = true;
    }
    return sb.toString();
}
like image 101
Jim Avatar answered Oct 29 '22 09:10

Jim


The way I've solved the problem is :

  1. SQL = "...WHERE ID NOT IN ({0}) ..."

  2. have a method which builds a string containing a number of ? equal to the size of SqlidList

    public static String buildQuestionMarks(final int count) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < count; i++) {
       sb.append("?" + ",");
    }
    return sb.substring(0, sb.length() - 1);
    

    }

  3. use java.text.MessageFormat.format() to insert the list of ? into the sql String finalSql = MessageFormat.format(SQL, questionMarksString);

  4. have a method to set the params on teh prepared statement. Something similar to what you wrote although you need to increment the first parameter of stat.setString()

This should work for variable number of parameters.

like image 44
Dan Iliescu Avatar answered Oct 29 '22 08:10

Dan Iliescu