IN clausule wih a PreparedStatement

Hi Folks,
Does anyone knows if there is any way to use the SQL clausule IN with a PreparedStatment? Could send me an example?
Thanks a lot!!

Sure you can.
Do you mean in the WHERE clause or the IN clause? You can do either, of course.
If I want to use bind parameters in the IN clause, I do it in two steps:
(1) Loop through once to append the IN clause to my SQL string, one question mark per entry,
(2) Loop through a second time to assign the values to the parameters.
But if I have the parameter values in a List already, and they don't require the services of the JDBC driver to escape them, I usually just enter them without using bind parameters. - MOD

Similar Messages

  • PreparedStatement parameter binding

    Hello,
    I am new to JDBC and java technology. I have experience with SQL, PL/SQL and I am quite shocked, that binding parameters using PreparedStatement class is based on parameter index instead of the parameter name.
    It is quite common in PL/SQL to use paramter name to bind a value to it.
    E.g. if I use query "select * from foo where id = :id and name = :name" I can bind parameters using dbms_sql.bind_variable(query, "id", 5) dbms_sql.bind_variable(query, "name", "london").
    However, in java I jave to bind using parameter index e.g query.setInt(1, 5), query.setString(2, new String("london")). Now the problems are
    - what if the sql programmer changes code "select * from foo where id = ? and name = ?" to "select * from foo where name = ? and id = ?"
    - think of a quite more complicated query, e.g. query with size of few kB - there can be a parameter repeated many times (id, date range etc) so I need to bind this parameter many times, instead of simple one bind by name
    - think of a dynamicaly generated query, where it is seriously complicated to follow the parameter indexes (sql block repeating, dynamicaly generated where clausules etc) and again binding by name is much more easier than indexed binding
    So my question is: Do you know of any class that supports binding by name ? Is there any workaround how to solve above mentioned issues ?
    And finally, what is the reason to use parameters by index instead of naming, which is I belive more obvious in database programming ?
    I am looking forward to your answers.
    Kindest regards,
    Kamil Poturnaj
    Mgr. Kamil Poturnaj, MicroStep-MIS
    Ilkovicova 3, 841 04 Bratislava, Slovakia

    - what if the sql programmer changes code "select *
    from foo where id = ? and name = ?" to "select * from
    foo where name = ? and id = ?"Tell him "please stop doing that" :-)
    He could also add a third parameter, "address = ?" which would also break it (even if the "?" were spelled ":address").
    The SQL statement and the code that binds / extracts values need to be modified in sync.
    - think of a quite more complicated query, e.g. query
    with size of few kB - there can be a parameter
    repeated many times (id, date range etc) so I need to
    bind this parameter many times, instead of simple one
    bind by nameThough I'm no great fan of vendor-specific 70-style languages, I'd recommend writing a PL/SQL procedure if a query gets very big.
    So my question is: Do you know of any class that
    supports binding by name ? Is there any workaround how
    to solve above mentioned issues ?I don't know of such a package; anyone...?
    It should be a nice programming exercise to write one. Something like:
        BindStatement stmt = new BindStatement("select a, :id from foo where id = :id and name = :name");
        stmt.set("name", "John");
        stmt.set("id", 1234);BindStatement would need to locate each occurrence of ":X" and create an SQL string with them replaced with "?"s. It would also need to store the positions where each ":X" occurred, so that when set("id",...) is called, it could do set(1,...); set(2,...); for the underlying statement.
    Occurrences of ":X" within strings need to be considered; the easy way is to replace there too.
    Unless I'm missing some gotcha, shouldn't take more than a couple of hours to write.
    And finally, what is the reason to use parameters by
    index instead of naming, which is I belive more
    obvious in database programming ?I can only speak from my experience: sql statements within Java code tend to be simple, and the "?" syntax is quite adequate there. Complex statements, if needed, are hidden in PL/SQL. Large systems use beans and automatically generated sql glue. This seems to be rarely a problem.

  • Open document issue using Xcelsius WIH 00013

    All,
    I have Open Document that behaves correctly when I copy and paste it into address bar of a browser. It also works fine when I try to connect from one Webi report to another (so far so good). But when I use the link in Xcelsius, via a URL component, I get the following message:
    Invalid Session: Please close your browser and logon again. (WIH 00013)
    Previous posts on forumtopics.com suggests that this is a Tomcat time out issue. However, other open document calls from other Xcelsius dashboards with open document work without issue. Has anyone seen this before? I have included the hyperlink text. Please note long prompt text is courtesy of a BEx query in BW .
    http://<web server>:8080/OpenDocument/opendoc/openDocument.jsp?iDocID=8547&lsSCompany%20Code%20(Single%20Value%20Entry%2C%20Required)=1000&lsSCurrent%20Fiscal%20Year%20(Single%20Value%20Entry%2C%20Mandatory)=2009&lsSFinancial%20statement%20version=cddFinancialStatements&lsSPosting%20Period%20(Single%20Value%20Entry%2C%20Mandatory)=003&lsSaccount=cdd+21
    Thanks,
    Steve

    The same settings in the infoviewapp web.xml must be applied on the opendocument web.xml. Also you must be on XI 3.1 FP1 or higher. There is currently an Edge issue being investigated.
    Regards,
    Tim

  • How to print Integrity sql in the preparedstatement?

    How to print Integrity sql in the preparedstatement?
    Connection conn = null;
    String sql = "select * from person where name=?";
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setObject(1, "robin");
    ps.executeQuery();
    i'm wants print Integrity sql.
    For example:select * from person where name='robin'
    How should I do?
    thanks a lot!

    PreparedStatement doesn't offer methods for that. You can write your own implementation of PreparedStatement which wraps the originating PreparedStatement and saves the set* values and writes it to the toString().
    If needed, myself I just print the sql as well as the values-being-set to the debug statement.Logger.debug(query + " " + values);

  • PreparedStatement not working

    Hi,
    I am having some problem using PreparedStatement.executeUpdate() . I want to be able to prepare several queries before commiting and I wrote this just to test it
    PreparedStatement stmt= aConnection.prepareStatement("update trans_test1 set field1='a text field' where field1='other text'");
              stmt.executeUpdate();
              aConnection.commit();
              stmt.close();
              aConnection.close();
    when it hits this line "stmt.executeUpdate();" the program just stops running and after a while throws this error.
    java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
    I set the auto commit to false but I still can't get it working and do not understand the problem. Any one can help?
    Thanks so much
    Alejo

    Hi,
    I am having some problem using
    PreparedStatement.executeUpdate() . I want to be able
    to prepare several queries before commiting and I
    wrote this just to test it
    PreparedStatement stmt=
    aConnection.prepareStatement("update trans_test1 set
    field1='a text field' where field1='other text'");
              stmt.executeUpdate();This is wrong in so many ways:
    (1) Use the bind variables.
    (2) Close resources properly in a finally block.
    (3) You don't show where you set auto commit to false
    (4) You don't show where you rollback in the event of a failure.
    >
    I set the auto commit to false but I still can't get
    it working and do not understand the problem. Any one
    can help?A snippet like this isn't enough. Post all the code.
    Which database are you using, and which driver?
    %

  • Oracle, SELECT IN and PreparedStatement.setArray

    I want to execute the following query: SELECT * FROM SOMETABLE WHERE IDFIELD IN (?)
    The number of values in the IN list is variable. How can I do this with a prepared statement?
    I am aware of the different alternatives:
    1) Keep a cache of prepared statement for each sized list seen so far.
    2) Keep a cache of prepared statements for different sizes (1, 5, 10, 20) and fill in the left over parameter positions with the copies first value.
    They both have the disadvantage that there could be many prepared statements for each query that get used once, and never used again.
    I have tried this:
    stmt.execute ("CREATE OR REPLACE TYPE LONGINTLIST AS TABLE OF NUMBER(15)");
    ArrayDescriptor desc = ArrayDescriptor.createDescriptor ("LONGINTLIST", conn);
    long idValues [] = {2, 3, 4};
    oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY (desc, conn, idValues);
    PreparedStatement query = conn.prepareStatement ("SELECT * FROM MYTABLE WHERE ID_FIELD IN (?)");
    query.setArray (1, paramArray);
    But Oracle gives a data conversion error.
    I then tried this:
    PreparedStatement query = conn.prepareStatement ("SELECT * FROM MYTABLE WHERE ID_FIELD IN (SELECT * FROM TABLE (?))");
    This works and the rows are returned, but the Oracle optimizer does not like it very much, since it always does a full table scan even though there is a primary key index on ID_FIELD.
    Any ideas?
    I also tried this:
    OraclePreparedStatement oraQuery = (OraclePreparedStatement) query;
    oraQuery.setARRAY (1, paramArray);
    But same behavior.
    Roger Hernandez

    Please re-read the original message. As I mentioned,
    I am aware of the two commonly used alternatives.No actually the most used alternative is to build the SQL dynamically each time.
    I know how to get both of them to work, and have used
    both alternatives in the past. The downside to both
    these approaches is that you need to save multiple
    prepared statements for each query. What I am trying
    to find is a way of having only one saved prepared
    statement for a query having a variable number of IN
    clause parameters.You could probably use a stored procedure that takes an 'array' and then do the processing in the stored proc to handle each array element.
    However, your database might not support that stored procs or arrays. Or it might not cache it with arrays. And the overhead of creating the array structure or processing it in the proc might eat any savings that you might gain (even presuming there is any savings) by using a prepared statement in the first place. Of course given that you must be using an automated profiling tool and have a loaded test environment you should be able to easily determine if this method saves time or not.
    Other than that there are no other solutions.

  • Problem with PreparedStatement

    I'm using a statement which needs to determine if the value is in a group.
    The statement will be
    "select name,age,occupation from personnel where age in ?"
    ps.setString(1, "(20,21,22)");
    I've also tried
    ps.setString(1, "('20','21','22')");
    Neither brings back any values in the result set.
    I can't figure out how to print what the preparedstatement looks like after setting the value.
    I look in the table and there are records with age 20, 21, 22.. and age is set as a string.

    Try this:
        query_B = "select tablename.blah_blah_blah"
                + "  from tablename"
                + " where tablename.etc is null"
                + "   and table.blah_term_code       in (?, ?)"
                + " order by 1, 2, 4, 7";
          String[] in_sem_dt = { "200307", "200308" };
          pstmt_B = con.prepareStatement( query_B );
          pstmt_B.setString( 1, in_sem_dt[0] );
          pstmt_B.setString( 2, in_sem_dt[1] );
          rs_B = pstmt_B.executeQuery();~Bill

  • Downloading images used to go automatically to the last folder used to save images, even when reopening Firefox. In just the past few days, possibly coinciding wih the most recent updates, the folder defaults to the 'Downloads' folder. This is most annoyi

    Downloading images used to go automatically to the last folder used to save images, even when reopening Firefox. In just the past few days, possibly coinciding wih the most recent updates, the folder defaults to the 'Downloads' folder. This is most annoying. What happened? Internet Explorer 8.0 did the same thing. This was one of the reasons why I started using Firefox to download all images. I went into Tools>Options and it only lets me set another folder. I dont want to set a specific folder I want it to always go to the last folder used. So what gives?
    == This happened ==
    Every time Firefox opened
    == possibly when the most recent updates were installed, a few days ago

    Thanks jscher 2000. I guess I didn't make it clear. "It restarts with all the addons activated, and resumes with the tabs that were open before closing it." IE, it's running fine now with all the extensions activated. Everything is OK now.
    So something in the Firefox code was causing the bad behavior. It's not essential that I find out what the problem was - I'm just curious. And if anybody else has this same problem, it might be nice to have it corrected at the source.

  • Closing PreparedStatements & ResultSets

    Is it necessary to explicitly close ResultSet AND PreparedStatement objects when used together? For example:
    PreparedStatement ps;
    ResultSet rs;
    String sql = " SELECT * FROM some_table WHERE id = ? ";
    try {
        ps = connection.prepareStatement(sql);
        ps.setString(1, someId);
        rs = ps.executeQuery();
        // And so on.....
    } finally {
      rs.close();
      ps.close();
    }Is it sufficient to close only the PreparedStatement? Does the ResultSet get cleaned up automatically when the PreparedStatement is closed? I don't want any lingering cursors left open, but at the same time, I don't want to write code that isn't needed. What's considered best form?
    Thanks.
    BTW: I'm using Oracle 8i/9i.

    I always close a Statement object, but don't worry about the ResultSet...that's really just a matter of redundancy...
    From the API on Statement.close()
    Note: A Statement object is automatically closed when it is garbage collected. When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

  • Too many connections - even after closing ResultSets and PreparedStatements

    I'm getting a "Too many connections" error with MySQL when I run my Java program.
    2007-08-06 15:07:26,650 main/CLIRuntime [FATAL]: Too many connections
    com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Too many connections
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:812)
            at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3269)
            at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1182)
            at com.mysql.jdbc.Connection.createNewIO(Connection.java:2670)I researched on this and found out that I wasn't closing the ResultSet and the PreparedStatement.
    The JDBC connection is closed by a central program that handles connections (custom connection pooling).
    I added the code to close all ResultSets and PreparedStatements, and re-started MySQL as per the instructions here
    but still get "Too many connections" error.
    A few other things come to mind, as to what I may be doing wrong, so I have a few questions:
    1) A few PreparedStatements are created in one method, and they are used in a 2nd method and closed in the 2nd method
    does this cause "Too many connections" error?
    2) I have 2 different ResultSets, in nested while loops where the outer loop iterates over the first ResultSet and
    the inner loop iterates over the second ResultSet.
    I have a try-finally block that wraps the inner while loop, and I'm closing the second ResultSet and PreparedStement
    in the inner while loop.
    I also have a try-finally block that wraps the outer while loop, and I'm closing the first ResulSet and PreparedStatement
    in the outer while loop as soon as the inner while loop completes.
    So, in the above case the outer while loop's ResultSet and PreparedStatements remain open until the inner while loop completes.
    Does the above cause "Too many connections" error?
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The following is relevant sections of my code ( it is partially pseudo-code ) that shows the above 2 cases:
    init( Connection jdbcConnection ){
       String firstSQLStatement = "....";
       PreparedStatement ps1 = jdbcConnection.prepareStatement( firstSQLStatement );
       String secondSQLStatement = "....";
       PreparedStatement ps2 = jdbcConnection.prepareStatement( secondSQLStatement );
       String thirdSQLStatement = "....";
       PreparedStatement ps3 = null;
       ResultSet rsA = null;
       try{
            ps3 = jdbcConnection.prepareStatement( thirdSQLStatement );
            rsA = ps3.executeQuery();
            if( rsA.next() ){
                   rsA.getString( 1 );
       }finally{
            if( rsA != null )
                   rsA.close();
            if( ps3 != null )
              ps3.close();
       //Notice, how ps1 and ps2 are created here but not used immediately, but only ps3 is
       //used immediately.
       //ps1 and ps2 are used in another method.
    run( Connection jdbcConnection ){
         ResultSet rs1 = ps1.executeQuery();
            try{
               while(rs1.next()){
                    String s = rs1.getString();
                    ps2.setString(1, s);
              ResultSet rs2 = ps2.executeQuery();
                    try{
                   while(rs2.next()){
                        String s2 = rs2.getString();
                    }finally{
                   if( rs2 != null )
                     rs2.close();
                   if( ps2 != null )
                     ps2.close();
         }catch( Exception e ){
              e.printStackTrace();
         }finally{
            if( rs1 != null )
                  rs1.close();
               if( ps1 != null )
                  ps1.close();
    //Notice in the above case rs1 and ps1 are closed only after the inner
    //while loop completes.
    }I appreciate any help.

    Thanks for your reply.
    I will look at the central connection pooling mechanism ( which was written by someone else) , but that is being used by many other Java programs others have written.
    They are not getting this error.
    An addendum to my previous note, I followed the instructions here.
    http://dev.mysql.com/doc/refman/5.0/en/too-many-connections.html
    There's probably something else in my code that is not closing the connection.
    But I just wanted to rule out the fact that opening a PreparedStatement in one method and closing it in another is not a problem.
    Or, if nested ResultSet loops don't cause the problem.
    I've read in a few threads taht "Too many connections" can occur for unclosed RS and PS , and not just JDBC connections.

  • Memory problems with PreparedStatements

    Driver: 9.0.1 JDBC Thin
    I am having memory problems using "PreparedStatement" via jdbc.
    After profiling our application, we found that a large number oracle.jdbc.ttc7.TTCItem objects were being created, but not released, even though we were "closing" the ResultSets of a prepared statements.
    Tracing through the application, it appears that most of these TTCItem objects are created when the statement is executed (not when prepared), therefore I would have assumed that they would be released when the ResultSet is close, but this does not seem to be the case.
    We tend to have a large number of PreparedStatement objects in use (over 100, most with closed ResultSets) and find that our application is using huge amounts of memory when compared to using the same code, but closing the PreparedStatement at the same time as closing the ResultSet.
    Has anyone else found similar problems? If so, does anyone have a work-around or know if this is something that Oracle is looking at fixing?
    Thanks
    Bruce Crosgrove

    From your mail, it is not very clear:
    a) whether your session is an HTTPSession or an application defined
    session.
    b) What is meant by saying: JSP/Servlet is growing.
    However, some pointers:
    a) Are there any timeouts associated with session.
    b) Try to profile your code to see what is causing the memory leak.
    c) Are there references to stale data in your application code.
    Marilla Bax wrote:
    hi,
    we have some memory - problems with the WebLogic Application Server
    4.5.1 on Sun Solaris
    In our Customer Projects we are working with EJB's. for each customer
    transaction we create a session to the weblogic application server.
    now there are some urgent problems with the java process on the server.
    for each session there were allocated 200 - 500 kb memory, within a day
    the JSP process on our server is growing for each session and don't
    reallocate the reserved memory for the old session. as a work around we
    now restart the server every night.
    How can we solve this problem ?? Is it a problem with the operating
    system or the application server or the EJB's ?? Do you have problems
    like this before ?
    greetings from germany,

  • PreparedStatement ResultSet wrapper to auto close cursor

    Hi !
    Is it possible to create wrapper that will automatically close result set and prepared statements ?
    I am sick of closing resultsets and preparedstatements in all my dao objects. Its all about neverending try catch and close code lines, it is all against the java garbage collector idea.
    Do you have any workaround ? Or I need to use with those try catch and close.
    Thanks !

    when u allocate object u dont need to call free nor destory when u dont need the object anymore.
    on the other hand, you need to call .close() when u dont need the prepared statement anymore

  • Setting a null(empty) binary stream in a PreparedStatement

    How can I bind a null binary stream into a PreparedStatement?
    In the following, if pMap is null how do I bind it? If I try to serialize a null pMap I get and error that not all columns bound.
    if(pMap == null)
    else
    byte[] _bytes = SerializeUtility.serializeObject(pMap);
    pStatement.setBinaryStream(pColCount, new ByteArrayInputStream(_bytes), _bytes.length);
    Thanks,
    David

    I was too close to the monitor, couldn't see the big picture ! :-) Now it works.
    Although, I still get that Websphere error:
    7c7fc721 SharedPool I J2CA0086W: Shareable connection MCWrapper id 31c73d Managed connection comm.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl@2e55c73d State:STATE_TRAN_WRAPPER_INUSE from resource jdbc/ds was used within a local transaction containment boundary.
    It use to work fine, no errors.
    Any ideeas??
    mihut

  • PreparedStatement and empty String instead of space

    Hi all, I would test a space value in a varchar field, i.e.:
    PreparedStatement ps=con.prepareStatement();
    String qry = "select a from table where b=? and c=?";
    ps.setString(1,"value");
    ps.setString(2," "); // space!!
    That source code doesn't work: it set "" (empty String) in the second field, not " " (space).
    Can I use PrepareStatement in any way to do this or I have to use only Statement?
    Thanks.
    Bye.

    my friend, the question was: how do you know the
    parameter is set to "" (empty string)?I don't know: I suppose!!! because it's the only reason for that it returns no record. I tested my query in this three ways:
    1) directly in sqlplus: SELECT OCCFASE As fase, OCLCVVC as convRat, SUM(QTA1) As qta1UM, SUM(QTA2) As qta2UM
    FROM DJITMPRE WHERE OCCFASE IN ('I','P') AND OCCCOSC='XXXXX' AND OCCITEM='RUG-02' AND OCCTPVR = 'RUG'
    AND OCCVAR1 = '01' AND OCCVAR2 = 'WW' AND OCCVAR3 = '12' AND OCCTPIM = '01' AND MAGAZZINO = 'MAG03'
    AND COMMESSA = ' ' AND ORIG = ' ' AND PARTITA = ' ' AND CONFIG = 0.0 AND VANO = ' '
    GROUP BY OCCFASE, OCLCVVC
    and it returns one record.
    2) using Statement:
         Statement s = conn.createStatement();
         String societa=session.getCompanyLogisticName(DSession.TABLE_LOGISTIC);
              StringBuffer qry=new StringBuffer();
              StringBuffer whereClause=new StringBuffer();
              qry.append("SELECT OCCFASE As fase, OCLCVVC as convRat, SUM(QTA1) As qta1UM, SUM(QTA2) As qta2UM ");
              qry.append("FROM DJITMPRE ");
              qry.append("WHERE OCCFASE IN ('I','P') ");
              qry.append("AND OCCCOSC='");
              qry.append(societa);
              qry.append("' ");     
              whereClause.append("AND OCCITEM='");
              whereClause.append(b.getItemCode());
              whereClause.append("' ");
              whereClause.append("AND OCCTPVR = '");
         if (b.getVariantType().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getVariantType(), 1));
         }else{
              whereClause.append(b.getVariantType());
         whereClause.append("' ");
         whereClause.append("AND OCCVAR1 = '");
         if (b.getFirstVariant().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getFirstVariant(), 1));
         }else{
              whereClause.append(b.getFirstVariant());
         whereClause.append("' ");
         whereClause.append("AND OCCVAR2 = '");
         if (b.getSecondVariant().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getSecondVariant(), 1));
         }else{
              whereClause.append(b.getSecondVariant());
         whereClause.append("' ");
         whereClause.append("AND OCCVAR3 = '");
         if (b.getThirdVariant().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getThirdVariant(), 1));
         }else{
              whereClause.append(b.getThirdVariant());
         whereClause.append("' ");
         whereClause.append("AND OCCTPIM = '");
         if (b.getPackingType().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getPackingType(), 1));
         }else{
              whereClause.append(b.getPackingType());
         whereClause.append("' ");
         whereClause.append("AND MAGAZZINO = '");
         if (b.getWarehouseCode().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getWarehouseCode(), 1));
         }else{
              whereClause.append(b.getWarehouseCode());
         whereClause.append("' ");
         whereClause.append("AND COMMESSA = '");
         if (b.getProjectItem().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getProjectItem(), 1));
         }else{
              whereClause.append(b.getProjectItem());
         whereClause.append("' ");
         whereClause.append("AND ORIG = '");
         if (b.getSourceLot().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getSourceLot(), 1));
         }else{
              whereClause.append(b.getSourceLot());
         whereClause.append("' ");
         whereClause.append("AND PARTITA = '");
         if (b.getLotNumber().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getLotNumber(), 1));
         }else{
              whereClause.append(b.getLotNumber());
         whereClause.append("' ");
         whereClause.append("AND CONFIG = ");
         whereClause.append(b.getItemConfiguration());
         whereClause.append("AND VANO = '");
         if (b.getLocation().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getLocation(), 1));
         }else{
              whereClause.append(b.getLocation());
         whereClause.append("' ");
         qry.append(whereClause.toString());
         qry.append(" GROUP BY OCCFASE, OCLCVVC");
    ResultSet rs = s.executeQuery(qry.toString());
    and it returns one record.
    3) using PreparedStatement:
    StringBuffer qry=new StringBuffer();
    qry.append("SELECT OCCFASE As fase, OCLCVVC as convRat, SUM(QTA1) As qta1UM, SUM(QTA2) As qta2UM ");
                   qry.append("FROM DJITMPRE WHERE OCCFASE IN ('I','P') ");
                   qry.append("AND OCCCOSC='").append(societa).append("' ");
                   qry.append("AND OCCITEM=? AND OCCTPVR = ? ");
              qry.append("AND OCCVAR1 = ? AND OCCVAR2 = ? AND OCCVAR3 = ? ");
              qry.append("AND OCCTPIM = ? AND MAGAZZINO = ? AND COMMESSA = ? ");
              qry.append("AND ORIG = ? AND PARTITA = ? AND CONFIG = ? ");
              qry.append("AND VANO = ? ");
              qry.append("GROUP BY OCCFASE, OCLCVVC");
    PreparedStatement bookedQtyPS = conn.prepareStatement(qry.toString());
    bookedQtyPS.setString(1,b.getItemCode());
         if (b.getVariantType().equals("")){
              bookedQtyPS.setString(2,EscapeString.getLengthString(b.getVariantType(), 1));
         }else{
              bookedQtyPS.setString(2,b.getVariantType());
         if (b.getFirstVariant().equals("")){
              bookedQtyPS.setString(3,EscapeString.getLengthString(b.getFirstVariant(), 1));
         }else{
              bookedQtyPS.setString(3,b.getFirstVariant());
         if (b.getSecondVariant().equals("")){
              bookedQtyPS.setString(4,EscapeString.getLengthString(b.getSecondVariant(), 1));
         }else{
              bookedQtyPS.setString(4,b.getSecondVariant());
         if (b.getThirdVariant().equals("")){
              bookedQtyPS.setString(5,EscapeString.getLengthString(b.getThirdVariant(), 1));
         }else{
              bookedQtyPS.setString(5,b.getThirdVariant());
         if (b.getPackingType().equals("")){
              bookedQtyPS.setString(6,EscapeString.getLengthString(b.getPackingType(), 1));
         }else{
              bookedQtyPS.setString(6,b.getPackingType());
         if (b.getWarehouseCode().equals("")){
              bookedQtyPS.setString(7,EscapeString.getLengthString(b.getWarehouseCode(), 1));
         }else{
              bookedQtyPS.setString(7,b.getWarehouseCode());
    //cat.debug("b.getProjectItem(): "+b.getProjectItem());
         if (b.getProjectItem().equals("")){
              //cat.debug("entro in 1 b.getProjectItem().length: "+b.getProjectItem().length());
              bookedQtyPS.setString(8,EscapeString.getLengthString(b.getProjectItem(), 1));
              //bookedQtyPS.setString(8," ");
         }else{
              //cat.debug("entro in 2 b.getProjectItem().length: "+b.getProjectItem().length());
              bookedQtyPS.setString(8,b.getProjectItem());
         bookedQtyPS.setString(8," ");
    //cat.debug("b.getSourceLot(): "+b.getSourceLot());     
         if (b.getSourceLot().equals("")){
              bookedQtyPS.setString(9,EscapeString.getLengthString(b.getSourceLot(), 1));
         }else{
              bookedQtyPS.setString(9,b.getSourceLot());
         bookedQtyPS.setString(9," ");
    //cat.debug("b.getLotNumber(): "+b.getLotNumber());     
         if (b.getLotNumber().equals("")){
              bookedQtyPS.setString(10,EscapeString.getLengthString(b.getLotNumber(), 1));
         }else{
              bookedQtyPS.setString(10,b.getLotNumber());
         bookedQtyPS.setString(10," ");
    //cat.debug("b.getItemConfiguration(): "+b.getItemConfiguration());
         bookedQtyPS.setString(11,""+b.getItemConfiguration());
    //cat.debug("b.getLocation(): "+b.getLocation());     
         if (b.getLocation().equals("")){
              bookedQtyPS.setString(12,EscapeString.getLengthString(b.getLocation(), 1));
         }else{
              bookedQtyPS.setString(12,b.getLocation());
         bookedQtyPS.setString(12," ");
    ResultSet rs = bookedQtyPS.executeQuery();
    and it returns 0 records.
    I hope I explained it well.

  • PreparedStatement space and empty String

    Hi, I have this problem:
    PreparedStatement bookedQtyPS = null;
    String qry="SELECT * from djwsearch where djwitem=?;
    bookedQtyPS = conn.prepareStatement(qry);
    if(item.equals(""){ //item is an empty String
    bookedQtyPS.setString(1," "); // I set space instead of empty String
    }else{
    bookedQtyPS.setString(1,item);
    My problem is that I need to set space insteadOf empty String, but I think that I can not use PreparedStatement to do this. I have performance problems (my query is much more complicated than this one) so I choose PreparedStatement and not Statement.
    How can I do? Is this bug solved using PreparedStatement?
    Thanks.

    you can do it with the help of PreparedStatement.
    Here the type of field(djwitem) and setmethod is should be match..i mean if the type of ur field is String then you need to use the setSting method.
    you can do one thing specify one string variable.
    String space=" ";
    and now put this sapce variable at the second parameter of setString method.

Maybe you are looking for

  • How to print a formatted page in java?

    hi all i've made my simple application that writes and retrieves information to/from a database, and organizes them in reports now, i got to print these reports in formatted pages like, for example: title centered and bold first db record second db r

  • Issue when creating a project form existing code

    Enviroment: Solaris 10 Oracle Solaris Studio I build a new project from existing code Set custom Makefile that use a GNU GCC Issue on C++ code assistance: - some times GCC C++ include file not found - some time doesn't find external include file - so

  • CPO on Activity Monitor over 100%

    I run Power eTrade Pro, a java based application with a continuous internet feed, and experience periods of over 100% CPU activity according to Activity Monitor. During those periods the program is frozen. This didn't happen with 10.4. It happens bot

  • The meaning included in the name of the model number of BlackBerry

    Hi All, I seem to get the meaning included in the name of the model number of BlackBerry devices. For example, I seem to have the rule in the second digit. I seem to have the rule in the alphabet. I want to know the outline of the spec from the model

  • I am unable to Open Firefox,Even after Reinstalling it,It Crashes in seconds loading homepage

    I am Unable open any page,It crashes after Loading homepage in seconds,i tried Reinstalling several times. -Kindly help!!! == This happened == Every time Firefox opened == I started my Desktop