1

I am using a MySQL database, a Java application and JDBC for communication.

The goal here is to select "Recipes" that match some criteria, which is achieved by not selecting (removing) certain recipes based on ID's

I am not especially strong in SQL, but the code below works just as intended when used in MySQL Workbench:

SELECT id FROM recipes WHERE(global_access = 1 OR owner = 1)
AND id NOT IN (1,2,3) 
AND id NOT IN ( 
# Remove for brevity. Returns ID's to be excluded. 
) );

Specifically, the part:

AND NOT IN (1,2,3)

should ensure that no recipes with ID 1,2 or 3 is returned. It coming as a String from Java in a PreparedStatement.

String sql = "SELECT id FROM recipes WHERE(global_access = 1 OR owner = ?) 
AND id NOT IN ( ? ) " .... (rest removed)

When I run this SQL in MySQL workbench, it correctly filters out the recipes (1,2,3). However, when I run it from Java, it does not.

I have checked that the parameter passed is indeed 1,2,3.

It does not give any errors, but seems to ignore the "AND NOT IN (1,2,3)" part completely.

Any idea how this can happen?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

1

Not every java database driver can do it, but often one can use a java.sql.Array:

AND id NOT IN(?)

Array a = connection.createArrayOf("INT", new Object[] {1, 2, 3});

preparedStatement.setArray(..., a);

Already commented, that setString would yield '1, 2, 3'.

The Array has to know the SQL type of every element, and for general usage is passed an Object array.


@MarkRotteveel informed this does not work in MySQL.

Then that part of the SQL string must be created dynamically.

" id NOT IN(" + idsList + ")"

Where idsList either is "?, ?, ... ?" needing setInt(++columnIndex, ids[i++]) or immediately "1, 2, 3".

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138