IN predicate in PreparedStatement?

How would you represent this using a PreparedStatement
DELETE FROM table WHERE id IN (....)
(.... is a list of integers that could be the id value)
Is it possible to assign a list of values using a single PreparedStatement '?'

The "in" version is, unsurprisingly, significantly faster for many items, since it doesn't have to do many network round trips to the database server.
With 100 items to delete, the program below shows the "in" version to be of the order of 30 times faster than 100 separate deletes. Your mileage will vary. E.g. if you delete using a non-indexed key from a table with a large number of rows, the full table scans will swamp the difference in network latency.
The significance of these differences will vary. If you do 10 deletes once in a blue moon, you won't care whether it takes 20 ms or 2 ms. But if you do that from e.g. a servlet in a busy web site, you will definitely care about SQL query latency.
Sample timings on an Oracle database:
with separate deletes: 297 ms
with separate deletes: 171 ms
with separate deletes: 174 ms
with separate deletes: 177 ms
with separate deletes: 212 ms
with separate deletes: 144 ms
with separate deletes: 153 ms
with separate deletes: 159 ms
with separate deletes: 131 ms
with separate deletes: 348 ms
with in statement: 6 ms
with in statement: 6 ms
with in statement: 12 ms
with in statement: 19 ms
with in statement: 5 ms
with in statement: 20 ms
with in statement: 4 ms
with in statement: 4 ms
with in statement: 4 ms
with in statement: 12 ms
import java.sql.*;
public class t
    public static void main(String args[])
        throws Exception
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        Connection connection = DriverManager.getConnection(args[0], args[1], args[2]);
        int delete_set_size = 100;
        PreparedStatement stmt = connection.prepareStatement("delete from sja where a = ?");
        for (int n = 0; n < 10; n++) {
            long start = System.currentTimeMillis();
            for (int m = 0; m < delete_set_size; m++) {
                stmt.setInt(1, m);
                stmt.executeUpdate();
            long end = System.currentTimeMillis();
            System.out.println("with separate deletes: " + (end - start) + " ms");
        stmt.close();
        for (int n = 0; n < 10; n++) {
            long start = System.currentTimeMillis();
            StringBuffer buf = new StringBuffer();
            buf.append("delete from sja where a in (");
            for (int m = 0; m < delete_set_size; m++) {
                if (m != 0)
                    buf.append(',');
                buf.append(m);
            buf.append(')');
            stmt = connection.prepareStatement(buf.toString());
            stmt.executeUpdate();
            stmt.close();
            long end = System.currentTimeMillis();
            System.out.println("with in statement: " + (end - start) + " ms");

Similar Messages

  • Using an IN predicate in a PreparedStatement

    Is there a clean way to handle the IN predicate in Oracle's PreparedStatement. I guess the obvious way to do it would be thus:
    ps = SELECT * FROM someTable WHERE id IN (?, ?, ?)
    But this means that every time you use a different number of IDs, you would create a new PreparedStatement. If the number of IDs is highly variable, you would end up polluting you statement cache with seldom-used PrepareStatements.
    Is there a easier way to send in a list of values for the IN predicate?

    Fred,
    You can try using an Oracle collection type, like VARRAY that maps to "java.sql.Array" and the TABLE [SQL] operator, but I don't know if this will perform better than a simple "IN" list.
    I think if you search the forum archives for ARRAY, you should find something relevant.
    Good Luck,
    Avi.

  • Date format for Task Predicate Query

    Does anyone know the correct format the task query is expecting when testing against flex field data e.g. dateAttribute1?
    I the following query ->
    <tas1:taskListRequest xmlns:com="http://xmlns.oracle.com/bpel/workflow/common" xmlns:tas="http://xmlns.oracle.com/bpel/workflow/taskQuery" xmlns:task="http://xmlns.oracle.com/bpel/workflow/task" xmlns:tas1="http://xmlns.oracle.com/bpel/workflow/taskQueryService">
        <tas:taskPredicateQuery startRow="0" endRow="200">
          <tas:displayColumnList>
            <tas:displayColumn>textAttribute1</tas:displayColumn>
            <tas:displayColumn>textAttribute2</tas:displayColumn>
            <tas:displayColumn>textAttribute3</tas:displayColumn>
            <tas:displayColumn>textAttribute4</tas:displayColumn>
            <tas:displayColumn>numberAttribute1</tas:displayColumn>
            <tas:displayColumn>dateAttribute1</tas:displayColumn>
          </tas:displayColumnList>
          <tas:optionalInfoList>
            <tas:taskOptionalInfo>Payload</tas:taskOptionalInfo>
          </tas:optionalInfoList>
          <tas:predicate>
            <tas:assignmentFilter>All</tas:assignmentFilter>
            <tas:clause joinOperator="AND" ignoreCase="true">
              <tas:column>STATE</tas:column>
              <tas:operator>EQ</tas:operator>
              <tas:value>ASSIGNED</tas:value>
            </tas:clause>
            <tas:clause joinOperator="AND">
              <tas:column>TITLE</tas:column>
              <tas:operator>EQ</tas:operator>
              <tas:value>Index Case</tas:value>
            </tas:clause>
            <tas:clause joinOperator="AND">
              <tas:column>dateAttribute1</tas:column>
              <tas:operator>BEFORE</tas:operator>
              <tas:value>2014-12-05T12:00:00</tas:value>
            </tas:clause>
          </tas:predicate>
        </tas:taskPredicateQuery>
      </tas1:taskListRequest>
    And get the following error ->
    <taskQueryServiceFaultResponse  xmlns="http://xmlns.oracle.com/bpel/workflow/taskQueryService">
          <message>
               ORA-30961:Invalid value specified in predicate clause.
              The value 2014-12-05T12:00:00 for column wfn.dateAttribute1 is invalid for the columns  data type.
              Specify a value that is of the correct type, or is another column with a matching  data type.
          </message>
    </taskQueryServiceFaultResponse>
    I have tried a number of formats and always get the same error!

    Of course you're right, thor_b. My point is that Oracle's "to_date" can convert a string to a date, but that's not how Access or SQL Server or any other RDBMS do it. They're all different. If you hardwire "to_date" into your SQL you'll have to rewrite the whole thing if you move from Oracle to SQL Server.
    I like the PreparedStatement because it takes care of all that for me.
    Performance penalty? Over Statement? I've read some stuff about that, but I find it hard to believe.
    Whenever you send SQL to a relational database it has to parse the SQL, determine if the tables and columns exist and have the right types, optimize the query, and then execute it. You have to do that whether you're using Statement or PreparedStatement. If PreparedStatement allows the RDBMS to do all that work once and then store it, I can't see how you'll do worse. - MOD

  • 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.

  • Index usage for retrieving data  without filter predicate

    Hi,
    does someone have a explanation for the following scenario:
    I have a table T1 with an index OID_IX on column ( object_id ) - The table is a CTAS from dba_objects just to populate it with data.
    There are no other Indexes present. The table and the index are analyzed !
    When I run the following query the table is accessed FULL ( not using the index )
    SELECT OBJECT_ID FROM T1;
    SQL> select object_id from t1;
    485984 rows selected.
    Elapsed: 00:00:01.76
    Execution Plan
    Plan hash value: 3617692013
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 485K| 2372K| 1528 (1)| 00:00:19 |
    | 1 | TABLE ACCESS FULL| T1 | 485K| 2372K| 1528 (1)| 00:00:19 |
    Statistics
    1 recursive calls
    0 db block gets
    7396 consistent gets
    0 physical reads
    0 redo size
    2887158 bytes sent via SQL*Net to client
    5684 bytes received via SQL*Net from client
    487 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    485984 rows processed
    But if I add a predicate ( even though it is useless in this case ) the index is taken and the query runs faster:
    JDBC@toekb> select object_id from t1 where object_id != -999;
    485960 rows selected.
    Elapsed: 00:00:01.40
    Execution Plan
    Plan hash value: 3555700789
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 485K| 2372K| 242 (3)| 00:00:03 |
    |* 1 | INDEX FAST FULL SCAN| OID_IX | 485K| 2372K| 242 (3)| 00:00:03 |
    Predicate Information (identified by operation id):
    1 - filter("OBJECT_ID"<>(-999))
    Statistics
    1 recursive calls
    0 db block gets
    1571 consistent gets
    0 physical reads
    0 redo size
    2766124 bytes sent via SQL*Net to client
    5684 bytes received via SQL*Net from client
    487 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    485960 rows processed
    here my setup:
    sqlsql--
    drop table t1 purge ;
    create table t1 tablespace users as select * from dba_objects;
    insert into t1 ( select * from t1);
    commit;
    insert into t1 ( select * from t1);
    commit;
    insert into t1 ( select * from t1);
    commit;
    create index oid_ix on t1 (object_id) tablespace users ;
    exec dbms_stats.gather_table_stats(null,'t1',cascade=>true, estimate_percent=>100);
    sqlsql--
    In my case the Table and Index looks this way:
    JDBC@toekb> select table_name, NUM_ROWS,BLOCKS,AVG_SPACE from user_tables;
    TABLE_NAME NUM_ROWS BLOCKS AVG_SPACE
    =======================================
    T1 485984 6944 0
    Elapsed: 00:00:00.11
    JDBC@toekb> select INDEX_NAME,BLEVEL,LEAF_BLOCKS,DISTINCT_KEYS,NUM_ROWS from user_indexes;
    INDEX_NAME BLEVEL LEAF_BLOCKS DISTINCT_KEYS NUM_ROWS
    ===================================================
    OID_IX 2 1074 60745 485960
    Elapsed: 00:00:00.07
    The table holds 7 times more blocks than the index !
    any reply welcome
    best regards
    Edited by: guenterp on Aug 12, 2010 2:44 PM

    guenterp wrote:
    Hi,
    does someone have a explanation for the following scenario:
    I have a table T1 with an index OID_IX on column ( object_id ) - The table is a CTAS from dba_objects just to populate it with data.
    There are no other Indexes present. The table and the index are analyzed !
    When I run the following query the table is accessed FULL ( not using the index )
    SELECT OBJECT_ID FROM T1;
    SQL> select object_id from t1;
    485984 rows selected.
    Elapsed: 00:00:01.76
    Execution Plan
    Plan hash value: 3617692013
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 485K| 2372K| 1528 (1)| 00:00:19 |
    | 1 | TABLE ACCESS FULL| T1 | 485K| 2372K| 1528 (1)| 00:00:19 |
    Statistics
    1 recursive calls
    0 db block gets
    7396 consistent gets
    0 physical reads
    0 redo size
    2887158 bytes sent via SQL*Net to client
    5684 bytes received via SQL*Net from client
    487 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    485984 rows processed
    But if I add a predicate ( even though it is useless in this case ) the index is taken and the query runs faster:
    JDBC@toekb> select object_id from t1 where object_id != -999;
    485960 rows selected.
    Elapsed: 00:00:01.40
    Execution Plan
    Plan hash value: 3555700789
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 485K| 2372K| 242 (3)| 00:00:03 |
    |* 1 | INDEX FAST FULL SCAN| OID_IX | 485K| 2372K| 242 (3)| 00:00:03 |
    Predicate Information (identified by operation id):
    1 - filter("OBJECT_ID"<>(-999))
    Statistics
    1 recursive calls
    0 db block gets
    1571 consistent gets
    0 physical reads
    0 redo size
    2766124 bytes sent via SQL*Net to client
    5684 bytes received via SQL*Net from client
    487 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    485960 rows processed
    here my setup:
    sqlsql--
    drop table t1 purge ;
    create table t1 tablespace users as select * from dba_objects;
    insert into t1 ( select * from t1);
    commit;
    insert into t1 ( select * from t1);
    commit;
    insert into t1 ( select * from t1);
    commit;
    create index oid_ix on t1 (object_id) tablespace users ;
    exec dbms_stats.gather_table_stats(null,'t1',cascade=>true, estimate_percent=>100);
    sqlsql--
    In my case the Table and Index looks this way:
    JDBC@toekb> select table_name, NUM_ROWS,BLOCKS,AVG_SPACE from user_tables;
    TABLE_NAME NUM_ROWS BLOCKS AVG_SPACE
    =======================================
    T1 485984 6944 0
    Elapsed: 00:00:00.11
    JDBC@toekb> select INDEX_NAME,BLEVEL,LEAF_BLOCKS,DISTINCT_KEYS,NUM_ROWS from user_indexes;
    INDEX_NAME BLEVEL LEAF_BLOCKS DISTINCT_KEYS NUM_ROWS
    ===================================================
    OID_IX 2 1074 60745 485960
    Elapsed: 00:00:00.07
    The table holds 7 times more blocks than the index !
    any reply welcome
    best regards
    Edited by: guenterp on Aug 12, 2010 2:44 PMSorry, but I am in doubt with your statists:
    Statistics
    1 recursive calls
    0 db block gets
    7396 consistent gets
    0 physical reads ---->>>>>>>>>>>> Why it is 0 in any case(bnoth full scan and index FFS)
    0 redo size
    2887158 bytes sent via SQL*Net to client
    5684 bytes received via SQL*Net from client
    487 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    485984 rows processedCould you pls retry below operation before execuion of each sql:
    alter system flush buffer_cache;In my case with 10.2.0.4 on HPUX:
    SQL> exec dbms_stats.gather_table_stats(null,'t1',cascade=>true, estimate_percent=>100);
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:03.61
    SQL> alter system flush buffer_cache;
    System altered.
    Elapsed: 00:00:14.00
    SQL> select * from t1;
    82016 rows selected.
    Elapsed: 00:00:06.48
    Execution Plan
    Plan hash value: 838529891
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      | 82016 |  6888K|   394   (1)| 00:00:05 |
    |   1 |  TABLE ACCESS FULL| T1   | 82016 |  6888K|   394   (1)| 00:00:05 |
    Statistics
              0  recursive calls
              0  db block gets
           6455  consistent gets
           1039  physical reads
              0  redo size
        3480570  bytes sent via SQL*Net to client
          38508  bytes received via SQL*Net from client
           5469  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          82016  rows processed
    SQL> alter system flush buffer_cache;
    System altered.
    Elapsed: 00:00:18.26
    SQL> select * from t1 where object_id !=999;
    81976 rows selected.
    Elapsed: 00:00:07.09
    Execution Plan
    Plan hash value: 838529891
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      | 81976 |  6884K|   394   (1)| 00:00:05 |
    |*  1 |  TABLE ACCESS FULL| T1   | 81976 |  6884K|   394   (1)| 00:00:05 |
    Predicate Information (identified by operation id):
       1 - filter("OBJECT_ID"<>999)
    Statistics
              0  recursive calls
              0  db block gets
           6443  consistent gets
           1039  physical reads
              0  redo size
        3478961  bytes sent via SQL*Net to client
          38494  bytes received via SQL*Net from client
           5467  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          81976  rows processed
    SQL>

  • 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

  • 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 do a bass slide?

    Hi all, Can anyone help me figure out how to do this kind of bass slide? I uploaded a small .wav file. I suspect you get a particular synth bass and do something with the pitch bend on the MIDI controller? If anyone knows of a particular present, say

  • Charm implemenation for transports in solman 7.1

    Hi Guru's, Can anyone help me to get knowledge in charm implementation for transports in solman. I am new to solman , can anyone help here. Help is much appreicated. Thanks, Pradeep.

  • Transition Icon not in Elements 11?

    In Pre Elements 7 there are Transition Icons between clips. When a clip is split a new icon appears. It is possible to place photos etc between clips by dragging to icon. The above in Sceneview in 7 & I am taking it that Quick in 11 is similar. Thre

  • Charging iPad 2 in uk

    I am traveling to the UK shortly and want to know if I can use my brothers UK apple chargers to charge my US devices. I will be taking iPad 2, iPad mini, iPhone 4S and iPod touch 4th gen. I want to avoid buying the charging kit unless absolutely nece

  • Can not create or use an account in Music Store

    I have tried every which way to create an account for the Music Store -- both via Apple and AOL Wallet, credit card and PayPal, but I can't seem to convince Music Store that I have an account at sign in time. Everytikme I try to Sign In, I get shuffl