Wednesday, August 28, 2013

How to set value/values(single or multiple) for IN clause in a preparedStatement in JDBC while executing a query.


Suppose we have a table states with following fields

state_id
state_name
country_name

If we want to find the states of india and canada then we will use the prepareStatement as follows

PreparedStatement pstmt = connection.prepareStatement("Select * from states where country_name in (?,?)");
pstmt.setString(1,"india","canada");
result = pstmt.executeQuery();

If we know the number of values which we want to use within in clause then it is very simple as above.
But when we dont know the values which we want to use within in clause then?
when we dont have any idea about the number of values with in IN clause then we will use  prepareStatement as follows.

String queryString = "Select * from states ";

Suppose we have a list of country names(countryNames) which is coming at run time.

StringBuffer sb = new StringBuffer();
for(int i = 0;i<countryNames.size();i++){
sb.append("?,");
}

queryString = queryString + " where country_name IN("+sb.deleteCharAt( sb.length() -1 ).toString()+") ";

pstmt = con.prepareStatement(queryString);
int index = 1;
for( String country : countryNames ) {
   pstmt.setString(  index++, country ); // or whatever it applies
}
result = pstmt.executeQuery();

Thursday, August 1, 2013

class and interface typecasting gotcha!!


 Suppose there are two classes First and Second

 class First{

 }

 class Second{

 }

 class First and Second has no relation(inheritance) and If we write the following statement.

 First obj =  (First)new Second(); // will give error at compile time.

 As all know it will give compile time error.

 But If First(which is class in above case) would be an interface then what would happen?

 Interface First{

 }

 class Second{

 }

 Now If we write the following statement

 First objNew =  (First)new Second(); // will not give compile time error.

 This statement does not give us the compile time error.
 Why this happens in case of interface?

 Reason - In case of Interface there may be a situation that any subclass of Second implements the First interface.Thats why in java type casting of interface is allowed(Because compile is not sure at compile time).

 If we make the class Second final then compiler is sure at compile time that there can't be any subclass of Second the it will give compile time error

 interface First{

 }

 final class Second{

 }

 First objNewer =  (First)new Second(); // will give compile time error