Search code examples
sqljdbcprepared-statementin-clause

multiple parameter "IN" prepared statement


I was trying to figure out how can I set multiple parameters for the IN clause in my SQL query using PreparedStatement.

For example in this SQL statement, I'll be having indefinite number of ?.

select * from ifs_db where img_hub = ? and country IN (multiple ?)

I've read about this in PreparedStatement IN clause alternatives?

However I can't figure it out how to apply it to my SQL statement above.


Solution

  • Sormula will work for any data type (even custom types). This example uses int's for simplicity.

    ArrayList<Integer> partNumbers = new ArrayList<Integer>();
    partNumbers.add(999);
    partNumbers.add(777);
    partNumbers.add(1234);
    
    // set up
    Database database = new Database(getConnection());
    Table<Inventory> inventoryTable = database.getTable(Inventory.class);
    
    ArrayListSelectOperation<Inventory> operation =
        new ArrayListSelectOperation<Inventory>(inventoryTable, "partNumberIn");
    
    // show results
    for (Inventory inventory: operation.selectAll(partNumbers))
        System.out.println(inventory.getPartNumber());