Tuesday 31 May 2016

PreparedStatemnet or CamelSqlQuery: using IN clause: IN clause appending to String Buffer,PreparedStatement with list of parameters in a IN clause

PreparedStatemnet or CamelSqlQuery: using IN clause: IN clause appending to String Buffer,PreparedStatement with list of parameters in a IN clause

public static void main(String args[]){
Connection connection = ConnectionManager.getConnection();
    PreparedStatement pstmt = null;
          //if the field values are in ArrayList
        List<String> fieldList = new ArrayList();

    try {

        StringBuffer sb = new StringBuffer();

        sb.append("  SELECT *            \n");
        sb.append("   FROM TEST          \n");
        sb.append("  WHERE FIELD IN (    \n");

        for(int i = 0; i < fieldList.size(); i++) {
            if(i == 0) {
                sb.append("    '"+fieldList.get(i)+"'   \n");
            } else {
                sb.append("   ,'"+fieldList.get(i)+"'   \n");
            }
        }
        sb.append("             )     \n");

        pstmt = connection.prepareStatement(sb.toString());
        pstmt.executeQuery();

    } catch (SQLException se) {
        se.printStackTrace();
    }

}

An other example:

package com.prabhu.inclause;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class InclausePreparedStmt {

public static void main(String[] args) {
List<BigInteger> listOfNumbers= new ArrayList<BigInteger>();
listOfNumbers.add(BigInteger.valueOf(101));
listOfNumbers.add(BigInteger.valueOf(105));
listOfNumbers.add(BigInteger.valueOf(104));
listOfNumbers.add(BigInteger.valueOf(343));
listOfNumbers.add(BigInteger.valueOf(534));
listOfNumbers.add(BigInteger.valueOf(741));
listOfNumbers.add(BigInteger.valueOf(735));
listOfNumbers.add(BigInteger.valueOf(823));
listOfNumbers.add(BigInteger.valueOf(165));
listOfNumbers.add(BigInteger.valueOf(328));

System.out.println("list: "+listOfNumbers);

StringBuffer buffer = new StringBuffer();
buffer.append("Select * from emp where empsal in  (\n");
for(int i=0;i<listOfNumbers.size();i++){
if(i==0){
buffer.append(" '"+listOfNumbers.get(i)+"' \n");
}
else{
buffer.append(" ,'"+listOfNumbers.get(i)+"' \n");
}
}
buffer.append("  )\n");
System.out.println("buffer: "+buffer);
}
}

No comments:

Post a Comment