Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL IN condition in Java

I have multiple conditions to check as shown below,

if(pouch.getStatus().equals("Finalized") || pouch.getStatus().equals("Ready") 
  || pouch.getStatus().equals("Checkout") || pouch.getStatus().equals("Confirmed")
  || pouch.getStatus().equals("Book") || pouch.getStatus().equals("Started")
  || pouch.getStatus().equals("Inital") || pouch.getStatus().equals("Close")) {
        // Body Implementation
}

Is there any easy way to check above conditions similar like SQL INcondition, so that code look simpler?

like image 300
Santosh Jadi Avatar asked Jun 16 '18 07:06

Santosh Jadi


People also ask

Is there an in operator in Java?

Java has no "in" operator. For arrays you need to iterate them and look for a matching item. For Lists you can use the contains method.

How can I use SQL in Java?

STEP 1: Allocate a Connection object, for connecting to the database server. STEP 2: Allocate a Statement object, under the Connection created earlier, for holding a SQL command. STEP 3: Write a SQL query and execute the query, via the Statement and Connection created. STEP 4: Process the query result.

How pass ArrayList as in clause in SQL query?

ArrayList<String> list = new ArrayList<String>(); PreparedStatement pstmt = conn. prepareStatement("select * from employee where id in (?)"); Array array = conn. createArrayOf("VARCHAR", list. toArray()); pstmt.

Can you use SQL and Java together?

Most Java developers interested in employing SQL in their work will do so through JDBC, which allows Java to connect to SQL databases.


1 Answers

Let's take a look about SQL in features

SQL WHERE IN returns values that match values in a list


So I would use a collection, which implements from Collection<E> and had contains method, make the if statement simpler.

contains(Object o) Returns true if this set contains the specified element.

contains effect is very similar to SQL in.


1.add your multiple conditions in the collection, which implements from Collection<E>

Set<String> dict = new HashSet<String>();
dict.add("Finalized");
dict.add("Ready");
dict.add("Checkout");
dict.add("Confirmed");
dict.add("Book");
dict.add("Started");
dict.add("Inital");
dict.add("Close");

2.using contains to check input value whether exist in the collection.

if (dict.contains(pouch.getStatus()))
{
     // do your logic
}
like image 162
D-Shih Avatar answered Sep 20 '22 03:09

D-Shih