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.

Similar Messages

  • Error IllegalArgumentException in java.sql.Date used PreparedStatement

    I'm found bug (probably). I have a table with column DATA type. Now I connect do database use JDBC in Java, and create PreparedStatement:
    PreparedStatement stmt = conn.prepareStatement("insert into \"Appuser\" (\"IDUser\", \"createAccountDate\") values (?,?)");
    Column createAccountDate is a DATA type. And now I invoke:
    stmt.setInt(1, 1);
    stmt.setInt(2, new java.sql.Date(-2508265596206959779));
    stmt.execute();
    and last line return exception:
    java.lang.IllegalArgumentException
    at sun.util.calendar.ZoneInfo.getOffset(ZoneInfo.java:368)
    at oracle.jdbc.driver.DateCommonBinder.zoneOffset(OraclePreparedStatement.java:15423)
    at oracle.jdbc.driver.DateCommonBinder.setOracleCYMD(OraclePreparedStatement.java:15561)
    at oracle.jdbc.driver.DateBinder.bind(OraclePreparedStatement.java:15641)
    at oracle.jdbc.driver.OraclePreparedStatement.setupBindBuffers(OraclePreparedStatement.java:2866)
    at oracle.jdbc.driver.OraclePreparedStatement.processCompletedBindRow(OraclePreparedStatement.java:2151)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3280)
    at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3390)
    at // line stmt.execute();
    Another values of Data are OK. Probably value -2508265596206959779 cause that error.
    It's a bug? Better will be SQLException if it is a bug.
    My configuration:
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    PL/SQL Release 10.2.0.1.0 - Production
    CORE     10.2.0.1.0     Production
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    Windows XP SP3, Java 1.6.0_20,
    ojdbc14.jar, Oracle JDBC Driver version - "10.2.0.1.0XE

    Probably value -2508265596206959779 cause that errorMaybe, whatever that .date( -ReallyLotsOfmSec ) date values is, pretty sure its outside the valid values for a date column, 4712BC to 9999AD is the min/max.
    Perhaps the java code can handle it, an oracle date type can not.

  • Use of PreparedStatement

    Hello friends,
    I need help in understanding how the PreparedStatement works.
    1. When we first create the PreparedStatement, database parse the sql statement and create the efficient access plan.
    2. Then database cache the sql and the access plan.
    3. When next time the request come for the same sql then database use the same access plan
    My question is if i close this prepared statement does the databse flush the sql and access plan stored in the cache???
    If ,some time later, I use the same sql in new PreparedStatement , wont the database use same access plan created earlier. I am using the same connection.
    Thanks in advance
    Rishi

    It's an involved subject but I'll try to answer:
    1. Yes and no. Yes, it does parse it, but I'm not sure when the plan is created. As to whether it is efficient...
    2. Yes
    3. Yes. I know this for Oracle, and I believe it for PostgresSQL. I expect that it is standard behaviour on any 'serious' RDBMS
    The database keeps the parsed SQL and the query plan in the SQL cache after you close the connection.
    This is an EXCELLENT reason why you should use prepared statements and bind variables instead of building new SQL each time.
    Parsing SQL and building query plans is hard work for a DBMS and it needs to hold latches (which are a kind of light weight lock ) on the system catalogs while it is doing that. Latches on the system catalog cause contention, serialization and reduced scalability. You might think that this is important only for very complicated SQL, but if your application is issuing thousands of different SQL statements like "SELECT * FROM customer WHERE customer_id = 1" (=2 , =211000 , = 27776, etc) then these simple selects will fill the sql cache at the expense of the complex SQL. Compare that to preparing "SELECT * FROM customer WHERE customer_id = ?" and using bind variables to supply the cusomer ID. That is 1 sql statement already parsed and planned that EVERY connection can use. And it will help make effective use of the SQL cache.
    As you can see, bind variables are actualy more important in this than using prepare, but prepare is good too. Bind variables have the potential to affect the scalabilty of your application perhaps even more than connection pooling.
    I refer you to "Effective Oracle By Design" by Thomas Kite, Oracle Press (Osborne) 50% of this book could be considered required reading for people who don't even use Oracle.

  • Error while adding attachments using attachmentLink

    Hi All,
    I am getting the below error sporadically while i add an attachment using my custom UI.
    The OA passivation framework coding standard has been violated. The view object with full name, xxCustomAM.oracle_apps_fnd_server_OAAttachmentsAM.Attach_1_FndDocumentsDomExtensionVO, is not properly prepared for row insertion. Either setMaxFetchSize(0) or executeQuery() (or any equivalent method that ends up executing the view object query) must be called on the view object before new rows are inserted. For a detail view object in a master - detail relationship, executeQuery() (or any equivalent method that ends up executing the view object query) must be called instead of setMaxFetchSize(0) on the detail view object before new rows are inserted into the detail view object. setMaxFetchSize(0) call on the detail view object could cause a number of adverse effects.
    The OA passivation framework coding standard has been violated. The view object with full name, xxCustomAM.oracle_apps_fnd_server_OAAttachmentsAM.Attach_1_FndAttachedDocumentsDomExtensionVO, is not properly prepared for row insertion. Either setMaxFetchSize(0) or executeQuery() (or any equivalent method that ends up executing the view object query) must be called on the view object before new rows are inserted. For a detail view object in a master - detail relationship, executeQuery() (or any equivalent method that ends up executing the view object query) must be called instead of setMaxFetchSize(0) on the detail view object before new rows are inserted into the detail view object. setMaxFetchSize(0) call on the detail view object could cause a number of adverse effects.
    The VO that I associate to the 'attachmentLink' is a detail VO. As I understand, before a row insertion we need to instantiate the detail VO using a false predicate like 'setWhereClause("1=0")'. From the above error, I see it uses setMaxFetchSize(0) instead, to insantiate the seeded VOs, FndDocumentsDomExtensionVO and FndAttachedDocumentsDomExtensionVO.
    Please let me know any suggestions to solve this.
    Regards,

    user611087 wrote:
    Thanks AJ for your immediate response.
    The VOs where the rows are getting created while we add attachments are FndDocumentsDomExtensionVO and FndAttachedDocumentsDomExtensionVO, which are seeded VOs.
    They belong to the seeded Application module, OAAttachmentsAM, which is the root application module to the attachment page.
    You mean, should I substitute the OAAttachmentsAM to add the above code? Since this is the root AM, we cannot do that rt?
    Regards,In such a case, you may write above code in extended controller.
    Thanks
    AJ

  • Not using Index when SDO_RELATE in Spatial Query is used in LEFT OUTER JOIN

    I want to know for every City (Point geometry) in which Municipality (Polygon geometry) it is.
    Some cities will not be covered by any municipality (as there is no data for it), so its municipality name should be blank in the result
    We have 4942 cities (point geometries)
    and 500 municipalities (polygon geometry)
    SELECT T1.NAME as City, T2.NAME as Municipality
    FROM CITY T1
    LEFT OUTER JOIN MUNICIPALITY T2 ON SDO_RELATE(T1.GEOM, T2.GEOM, 'MASK=ANYINTERACT') = 'TRUE'The explain plan for this query is:
    SELECT STATEMENT
      FILTER
        Filter Predicates
          MDSYS.SDO_RTREE_RELATE(T1.GEOM, T2.GEOM, 'mask=ANYINTERACT querytype=window ') = 'TRUE'
        MERGE JOIN
          TABLE ACCESS              CITY               FULL                            11
          BUFFER                                       SORT                        100605
              TABLE ACCESS          MUNICIPALITY       FULL                            20So the cost is in the BUFFER (whatever that is), it takes +2000 seconds to run this, it is not using the spatial index.
    And we are not getting all rows, but only the ones interacting with a municipality, e.g. 2436 rows.
    But I want all rows, including the ones not interacting with any Municipality.
    When we want only those cities that actually are in a municipality, I use a different query and it will use the index.
    SELECT T1.NAME as City, T2.NAME as Municipality
    FROM CITY T1, MUNICIPALITY T2
    WHERE SDO_RELATE(T1.GEOM, T2.GEOM, 'MASK=ANYINTERACT') = 'TRUE'I get (only) 2436 rows (as expected) in 5 seconds (it is fast) and the explain plan shows it is using the spatial index.
    But in this case, I am not getting any cities not inside any municipality (of course)
    SELECT STATEMENT
       NESTED LOOPS
          TABLE ACCESS                   MUNICIPALITY       FULL                22
          TABLE ACCESS                   CITY               BY INDEX ROWID      22
             DOMAIN INDEX                CITY_SDX                                0
                Access Predicates
                   MDSYS.SDO_RTREE_RELATE(T1.GEOM, T2.GEOM, 'mask=ANYINTERACT querytype=window ') = 'TRUE'I always thought a LEFT OUTER JOIN would return all rows from the Table, whatever happens in the next,
    but it seems the query has been rewritten so that it is now using a Filter Predicate in the end, which filters those geometries having no interaction.
    As an example I also do thing alphanumerically, I do get 4942 rows, including the ones which have no Municipality name.
    In this case the names must match, so its only for testing if the LEFT OUTER JOIN returns stuff correctly, which it does in this case.
    SELECT T1.NAME as City, T2.NAME as Municipality
    FROM CITY T1
    LEFT OUTER JOIN MUNICIPALITY T2 ON T1.NAME = T2.NAMEIs this an Oracle Spatial bug, e.g. not return 4942 rows, but only 2436 rows on the first query?
    Note all tests performed on Oracle 11g R2 (11.2.0.1.0)

    Patrick,
    Even so, your geoms in the relate were the wrong way around.
    Also, I don't recall you saying (or showing) that you wanted the municipality geometry returned. Still,
    no matter, easy to do.
    Here are some additional suggestions. I don't have your data so I have had to use some of my own.
    set serveroutput on timing on autotrace on
    SELECT T1.SPECIES as City,
           (SELECT T2.ADMIN_NAME FROM AUSTRALIAN_STATES T2 WHERE SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE') as Municipality,
           (SELECT T2.GEOM       FROM AUSTRALIAN_STATES T2 WHERE SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE') as geom
      FROM GUTDATA T1;
    762 rows selected
    Elapsed: 00:00:21.656
    Plan hash value: 2160035213
    | Id  | Operation                   | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |                            |   762 | 49530 |     5   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| AUSTRALIAN_STATES          |     1 |   115 |     0   (0)| 00:00:01 |
    |*  2 |   DOMAIN INDEX              | AUSTRALIAN_STATES_GEOM_SPX |       |       |     0   (0)| 00:00:01 |
    |   3 |  TABLE ACCESS BY INDEX ROWID| AUSTRALIAN_STATES          |     1 |   115 |     0   (0)| 00:00:01 |
    |*  4 |   DOMAIN INDEX              | AUSTRALIAN_STATES_GEOM_SPX |       |       |     0   (0)| 00:00:01 |
    |   5 |  TABLE ACCESS FULL          | GUTDATA                    |   762 | 49530 |     5   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"(:B1,10000,0.5,'UNIT=M'))='TRUE')
       4 - access("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"(:B1,10000,0.5,'UNIT=M'))='TRUE')
       Statistics
                   7  user calls
               24576  physical read total bytes
                   0  physical write total bytes
                   0  spare statistic 3
                   0  commit cleanout failures: cannot pin
                   0  TBS Extension: bytes extended
                   0  total number of times SMON posted
                   0  SMON posted for undo segment recovery
                   0  SMON posted for dropping temp segment
                   0  segment prealloc tasksThe above can look messy as you add more (SELECT ...) attributes, but is is fast (though can't use in Materialized Views).
    /* The set of all cities not in municipalities */
    SELECT T1.SPECIES                 as City,
           cast(null as varchar2(42)) as municipality,
           cast(null as sdo_geometry) as geom
      FROM GUTDATA T1
    WHERE NOT EXISTS (SELECT 1
                         FROM AUSTRALIAN_STATES T2
                        WHERE SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE')
    UNION ALL
    /* The set of all cities in municipalities */
    SELECT T1.SPECIES    as City,
           T2.ADMIN_NAME as Municipality,
           T2.GEOM       as geom
      FROM GUTDATA T1
           INNER JOIN
           AUSTRALIAN_STATES T2 ON (SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE');
    762 rows selected
    Elapsed: 00:00:59.953
    Plan hash value: 2854682795
    | Id  | Operation           | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |                            |    99 | 13450 |    38  (87)| 00:00:01 |
    |   1 |  UNION-ALL          |                            |       |       |            |          |
    |*  2 |   FILTER            |                            |       |       |            |          |
    |   3 |    TABLE ACCESS FULL| GUTDATA                    |   762 | 49530 |     5   (0)| 00:00:01 |
    |*  4 |    DOMAIN INDEX     | AUSTRALIAN_STATES_GEOM_SPX |       |       |     0   (0)| 00:00:01 |
    |   5 |   NESTED LOOPS      |                            |    61 | 10980 |    33   (0)| 00:00:01 |
    |   6 |    TABLE ACCESS FULL| AUSTRALIAN_STATES          |     8 |   920 |     3   (0)| 00:00:01 |
    |*  7 |    TABLE ACCESS FULL| GUTDATA                    |     8 |   520 |     4   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - filter( NOT EXISTS (SELECT 0 FROM "AUSTRALIAN_STATES" "T2" WHERE "MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"(:B1,10000,0.5,'UNIT=M'))='TRUE'))
       4 - access("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"(:B1,10000,0.5,'UNIT=M'))='TRUE')
       7 - filter("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"("T1"."GEOM",10000,0.5,'UNIT=M'))='TRUE')
       Statistics
                   7  user calls
              131072  physical read total bytes
                   0  physical write total bytes
                   0  spare statistic 3
                   0  commit cleanout failures: cannot pin
                   0  TBS Extension: bytes extended
                   0  total number of times SMON posted
                   0  SMON posted for undo segment recovery
                   0  SMON posted for dropping temp segment
                   0  segment prealloc tasksMuch slower but Materialized View friendly.
    This one is a bit more "natural" but still slower than the first.
    set serveroutput on timing on autotrace on
    /* The set of all cities in municipalities */
    WITH municipal_cities As (
      SELECT T1.ID         as City,
             T2.ADMIN_NAME as Municipality,
             T2.GEOM       as geom
        FROM GUTDATA T1
             INNER JOIN
             AUSTRALIAN_STATES T2 ON (SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE')
    SELECT T1.ID           as City,
           T2.Municipality as Municipality,
           T2.GEOM         as geom
      FROM GUTDATA          T1
           LEFT OUTER JOIN
           municipal_cities T2
           ON (T2.CITY = T1.ID);
    762 rows selected
    Elapsed: 00:00:50.228
    Plan hash value: 745978991
    | Id  | Operation             | Name              | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT      |                   |   762 | 44196 |    36   (3)| 00:00:01 |
    |*  1 |  HASH JOIN RIGHT OUTER|                   |   762 | 44196 |    36   (3)| 00:00:01 |
    |   2 |   VIEW                |                   |    61 |  3294 |    33   (0)| 00:00:01 |
    |   3 |    NESTED LOOPS       |                   |    61 | 10980 |    33   (0)| 00:00:01 |
    |   4 |     TABLE ACCESS FULL | AUSTRALIAN_STATES |     8 |   920 |     3   (0)| 00:00:01 |
    |*  5 |     TABLE ACCESS FULL | GUTDATA           |     8 |   520 |     4   (0)| 00:00:01 |
    |   6 |   INDEX FAST FULL SCAN| GUTDATA_ID_PK     |   762 |  3048 |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - access("T2"."CITY"(+)="T1"."ID")
       5 - filter("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"("T1"."GEOM",10000,0.5,'UNIT=M'))='TRUE')
       Statistics
                   7  user calls
               49152  physical read total bytes
                   0  physical write total bytes
                   0  spare statistic 3
                   0  commit cleanout failures: cannot pin
                   0  TBS Extension: bytes extended
                   0  total number of times SMON posted
                   0  SMON posted for undo segment recovery
                   0  SMON posted for dropping temp segment
                   0  segment prealloc tasksFinally, the Pièce de résistance: trick the LEFT OUTER JOIN operator...
    set serveroutput on timing on autotrace on
    SELECT T1.SPECIES    as City,
           T2.ADMIN_NAME as Municipality,
           T2.GEOM       as geom
      FROM GUTDATA           T1
           LEFT OUTER JOIN
           AUSTRALIAN_STATES T2
           ON (t2.admin_name = to_char(t1.ID) OR
               SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE');
    762 rows selected
    Elapsed: 00:00:50.273
    Plan hash value: 158854308
    | Id  | Operation           | Name              | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |                   |   762 | 92964 |  2294   (1)| 00:00:28 |
    |   1 |  NESTED LOOPS OUTER |                   |   762 | 92964 |  2294   (1)| 00:00:28 |
    |   2 |   TABLE ACCESS FULL | GUTDATA           |   762 | 49530 |     5   (0)| 00:00:01 |
    |   3 |   VIEW              |                   |     1 |    57 |     3   (0)| 00:00:01 |
    |*  4 |    TABLE ACCESS FULL| AUSTRALIAN_STATES |     1 |   115 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       4 - filter("T2"."ADMIN_NAME"=TO_CHAR("T1"."ID") OR
                  "MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"("T1"."GEOM",10000,0.5,'UNIT=M'))='TRUE')
       Statistics
                   7  user calls
                   0  physical read total bytes
                   0  physical write total bytes
                   0  spare statistic 3
                   0  commit cleanout failures: cannot pin
                   0  TBS Extension: bytes extended
                   0  total number of times SMON posted
                   0  SMON posted for undo segment recovery
                   0  SMON posted for dropping temp segment
                   0  segment prealloc tasksTry these combinations to see what works for you.
    Interestingly, for me, the following returns absolutely nothing.
    SELECT T1.SPECIES    as City,
           T2.ADMIN_NAME as Municipality
      FROM GUTDATA           T1
           LEFT OUTER JOIN
           AUSTRALIAN_STATES T2
           ON (SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE')
    MINUS
    SELECT T1.SPECIES    as City,
           T2.ADMIN_NAME as Municipality
      FROM GUTDATA           T1
           LEFT OUTER JOIN
           AUSTRALIAN_STATES T2
           ON (t2.admin_name =  to_char(t1.ID) OR
               SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE');(I leave it to you to see if you can see why as the LEFT OUTER JOIN seems to be working correctly for me but I am not going to dedicate time to detailed checking of results.)
    Note all tests performed on Oracle 11g R2 (11.2.0.1.0)
    If you get the answer you want: mark the post as answered to assign points.
    regards
    Simon

  • Using DBMS_SQL getting ORA-29255

    Sort of new to DBMS_SQL - as I've been using NDS for almost everything to this point.
    However - I have a situation where I'm selecting data that requires a predicate of multiple values for a single column (i.e. column in (:v1)) where :v1 is a list of values. I was using bind_array to set the values for :v1. However - I get the error above.
    The SQL returns mutiple rows so - define array is being used to indicate what column should be returned to what array.
    I understand based on the error message that they can't be used together. So- my question is - when using a SQL statement that requires "columnA IN (multiple_values)" how are you supposed to bind those using DBMS_SQL?
    Any help is appreciated!!

    Thanks... Code is below...
    You can see where the vspccat is a predicate and - we're trying to get the multiple values 'bound' to the SQL. However - the sql also returns multiple rows (hence the 'define array' to get the return values).
    We're using DBMS_SQL over NDS simply because (as isn't illustrated in the example below - which I was using just to get the concept working in an example to use moving forward with the actual code I will need to write) I'm needing to use multiple varrying predicates depending on the situation and - this is a cleaner way to handle that - rather than tracking what's been dynamically written and - handling it with every possible scenario in many different executes (with the different 'using's' attached).
    Your help is appreciated!
    DECLARE
    col1    NUMBER(9,0);
    col2    VARCHAR2(15);
    col3    VARCHAR2(15);
    col4    VARCHAR2(60);
    col5    DATE;
    col6    DATE;
    col7    VARCHAR2(6);
    col8    NUMBER(9,0);
    col9    VARCHAR2(1);
    spc_cat_array   DBMS_SQL.VARCHAR2_TABLE;
    col1_array      DBMS_SQL.NUMBER_TABLE;
    col2_array      DBMS_SQL.VARCHAR2_TABLE;
    col3_array      DBMS_SQL.VARCHAR2_TABLE;
    col4_array      DBMS_SQL.VARCHAR2_TABLE;
    col5_array      DBMS_SQL.DATE_TABLE;
    col6_array      DBMS_SQL.DATE_TABLE;
    col7_array      DBMS_SQL.VARCHAR2_TABLE;
    col8_array      DBMS_SQL.NUMBER_TABLE;
    col9_array      DBMS_SQL.VARCHAR2_TABLE;
    p_spc_cat   VARCHAR2(15) := '03';
    p_status    VARCHAR2(6)  := 'APPROV';
    src_cur  INTEGER;
    dest_cur INTEGER;
    ignore   INTEGER;
    fdbk     INTEGER;
    l_sql   VARCHAR2(1000);
    dest_rec    VARCHAR2(500);
    BEGIN
        spc_cat_array(1) := '03';
        spc_cat_array(2) := '09';    
        spc_cat_array(3) := '35';
        l_sql := ' SELECT *' ||
                      ' FROM (SELECT maint_id, NULL AS ica_price_rule, spc_category, description,' ||
                                   ' effective_date, term_date, status,' ||
                                   ' seq_ica_spc_pr_whole AS sequence_id, update_type' ||
                              ' FROM ica_spc_pr_whole_hdr_wrk' ||
                                ' WHERE spc_category IN (:vspccat)' ||
                                ' AND status = :vstatus  ' ||
                                ' AND term_date IS NULL' ||
                             ' UNION ALL' ||
                            ' SELECT NULL AS maint_id, NULL AS ica_price_rule, spc_category,' ||
                                   ' description, effective_date, term_date, status,' ||
                                   ' seq_ica_spc_pr_whole AS sequence_id, NULL AS update_type' ||
                              ' FROM ica_spc_pr_whole_hdr live'  ||
                                ' WHERE spc_category IN (:vspccat)' ||
                                ' AND status = :vstatus  ' ||
                                ' AND term_date IS NULL' ||
                               ' AND NOT EXISTS (SELECT spc_category' ||
                                                 ' FROM ica_spc_pr_whole_hdr_wrk wrk' ||
                                                ' WHERE wrk.spc_category = live.spc_category)) a';
        -- open cursor on source table
      src_cur := dbms_sql.open_cursor;
      -- parse the SELECT statement
      dbms_sql.parse(src_cur, l_sql, dbms_sql.NATIVE);
      -- Bind Variables
    --  DBMS_SQL.BIND_VARIABLE (src_cur, ':vspccat', p_spc_cat);
      DBMS_SQL.BIND_ARRAY (src_cur, ':vspccat', spc_cat_array);
      DBMS_SQL.BIND_VARIABLE (src_cur, ':vstatus', p_status);
      -- define the column type
      dbms_sql.define_array(src_cur, 1, col1_array, 5, 1);
      dbms_sql.define_array(src_cur, 2, col2_array, 5, 1);
      dbms_sql.define_array(src_cur, 3, col3_array, 5, 1);
      dbms_sql.define_array(src_cur, 4, col4_array, 5, 1); 
      dbms_sql.define_array(src_cur, 5, col5_array, 5, 1);
      dbms_sql.define_array(src_cur, 6, col6_array, 5, 1);
      dbms_sql.define_array(src_cur, 7, col7_array, 5, 1);
      dbms_sql.define_array(src_cur, 8, col8_array, 5, 1);
      dbms_sql.define_array(src_cur, 9, col9_array, 5, 1);
      ignore := dbms_sql.execute(src_cur);
      if dbms_sql.fetch_rows(src_cur) > 0  then
              dbms_sql.column_value( src_cur, 1, col1_array);
              dbms_sql.column_value( src_cur, 2, col2_array);
              dbms_sql.column_value( src_cur, 3, col3_array);
              dbms_sql.column_value( src_cur, 4, col4_array);
              dbms_sql.column_value( src_cur, 5, col5_array);
              dbms_sql.column_value( src_cur, 6, col6_array);
              dbms_sql.column_value( src_cur, 7, col7_array);
              dbms_sql.column_value( src_cur, 8, col8_array);
              dbms_sql.column_value( src_cur, 9, col9_array);         
          end if;
        dbms_output.put_line(col3_array(1));
      dbms_sql.close_cursor(src_cur);
    end;

  • Problem with GenericCatalogDAO  JDBC Resultset using parameters not working

    Hello
    I have a problem with Petstore GenericCatalogDAO. java. The problem is the behaviour of the resultset object when retrieving data from the database.Below are two synareos one that
    works (when) hard coded and one that does not work when parameter values passed into the the result set.
    1. The code the WORKS.
    statement = connection.prepareStatement("select a.productid , name, descn from product a, product_details b
    where a.productid = b.productid and locale= 'en_US' and a.catid = 'FISH' order by name"
    ,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    resultSet = statement.executeQuery();
    resultSet.absolute(1);
    String s = resultSet.getString(1);
    The code that gives me a 'exhausted resultset' error which I think means no results
    String[] parameterValues = new String[] { locale.toString(), categoryID };(For example parameters are 'en_US' and 'FISH')
    statement = connection.prepareStatement("select a.productid , name, descn from product a, product_details b
    where a.productid = b.productid and locale=? and a.catid =? order by name"
    ,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    for (int i = 0; i < parameterValues.length; i++) {
    statement.setString(i + 1, parameterValues[i]);
    resultSet = statement.executeQuery();
    resultSet.absolute(1);
    String s = resultSet.getString(1);
    There is obviously a problem using these named parametevalues with these preparedstatement resultset, Does anybody know anything about this and a fix for it????
    Cheers. Roger

    Which version of PetStore are you using?
    -Larry

  • Prepared statement problem using a field name that contains a "?"

    I am attempting to execute the following query via use of a PreparedStatement:
    select [Spread_By_Cost_Center?], Debit_Category, Credit_Category, Start_Date, End_Date, Allocation_Type From ALLOCATION_FORMULA Where FormulaID = ?
    The query fails with the following message:
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT
    field incorrect
    However, I can run this query directly in MS-ACCESS, using a value for the substitution parameter (i.e., FormulaID = 1)
    If I remove the "Spread_By_Cost_Center? field from the query within the PreparedStatement, the PreparedStatement query executes successfully.
    So, it would appear that the "?" in the field name is possibly being treated as a substitution parameter. Is this a bug within PreparedStatement? I do not want to use a Statement object, as the PreparedStatement provides a much more elegant solution (when it works).
    Any suggestions?

    That may be so, but as I see it there are two alternatives:
    1. Wait for the "bug" to be fixed.
    2. Change the database to use less problematic column names.
    I know which alternative I would choose.

  • Creating a point geometry with coordinate transformation using JDBC

    If I execute the following SQL statement using a tool such as TOAD then I get a correct value for the point in the oracle column.
    INSERT INTO node (id, position) VALUES (53, SDO_CS.TRANSFORM(SDO_GEOMETRY(2001, 26910, SDO_POINT_TYPE(489535.0, 5457841.0, NULL), NULL, NULL), 4269))
    Point geometry:
    (2001, 4269, (-123.143865452971, 49.2732377100255, ), , )
    If I execute the same statement using JDBC in a Statement or PreparedStatement the Point in the oracle column has 0,0 for the coordinates.
    Point: geometry
    (2001, 4269, (0, 0, ), , )
    In both cases the SQL is exactly the same.
    my JDBC code is
    String insertSql = "INSERT INTO node (id, position) VALUES (" + id
    + ", SDO_CS.TRANSFORM(SDO_GEOMETRY(2001, " + geometrySrid
    + ", SDO_POINT_TYPE(" + coordinate2d.x + ", " + coordinate2d.y
    + ", NULL), NULL, NULL), " + srid + "))";
    Statement insertStatement = connection.createStatement();
    try {
    insertStatement.execute(insertSql);
    } finally {
    JdbcUtils.closeStatement(insertStatement);
    connection.commit();
    Any ideas why this is happening?
    I've tried to do the coordinate transformation in a separate call and pass in the STRUCT returned from that, using JGeometry to create a STRUCT for the value, using a WKT geometry and none of these approaches seem to work

    Paul,
    I have seen this work using JGeometry and STRUCT objects with PreparedStatements. Here's some sample code that seems to work just fine:
    ResultSet rs = null;
    try {
    PreparedStatement ps =
    getConn().prepareStatement("select SDO_CS.TRANSFORM(?, ?) from dual");
    /* constucts JGeometry objects using simple points (doubles) and SRID
    * Per the Javadoc, JGeometry objects can be constructed using the same
    * notation and signature as SDO_GEOMETRY objects -
    * JGeometry(int gtype, int srid, double x, double y, double z, int[] elemInfo, double[] ordinates) */
    JGeometry j_geom1 = new JGeometry(-122.4, 37.8, 8265);
    int newSRID = 4269;
    //convert JGeometry instances to DB STRUCT
    STRUCT obj1 = JGeometry.store(j_geom1, getConn());
    ps.setObject(1, obj1);
    ps.setInt(2, newSRID);
    rs = ps.executeQuery();
    while (rs.next()) {
    //System.out.println(rs.getString(1));
    STRUCT st = (oracle.sql.STRUCT) rs.getObject(1);
    JGeometry j_geom = JGeometry.load(st);
    System.out.println(j_geom);
    ps.close();
    rs.close();
    conn.close();
    } catch (Exception e) {
    System.err.print(e);
    Hope this helps.
    -Justin

  • Select Query where multiple column in multiple values (cant use in clause)

    I can use (in clause) with on column like this:
    Select code from table where code in(1,2,3)
    -------------------------------My case:-------------------------------------------------
    I’ve 4 columns PK of table as below 
    I need to :
    select
    where (code, month, year) in ((1,1,2013) and (2,1,2014) and (2,2,2015))
    i can't write it this way :
    select where code in (1,2) and month in (1,2) and year in (2013,2014,2015)
    case i'll get my rows but others included like (1,1,2015) , (1,1,2014),(2,1,2013) .. etc
    I’m terribly want to solve this problem
    Please help me
    Code (pk)
    Month (pk)
    Year (pk)
    emp_code(pk)
    1
    1
    2013
    101
    1
    1
    2013
    102
    2
    1
    2013
    101
    2
    1
    2013
    102
    1
    2
    2013
    101
    1
    2
    2013
    102
    2
    2
    2013
    101
    2
    2
    2013
    102
    1
    1
    2014
    101
    1
    1
    2014
    102
    2
    1
    2014
    101
    2
    1
    2014
    102
    1
    2
    2014
    101
    1
    2
    2014
    102
    2
    2
    2014
    101
    2
    2
    2014
    102
    1
    1
    2015
    101
    1
    1
    2015
    102
    2
    1
    2015
    101
    2
    1
    2015
    102
    1
    2
    2015
    101
    1
    2
    2015
    102
    2
    2
    2015
    101
    2
    2
    2015
    102
    thank you

    In T-SQL you have to use OR-ed predicates. 
    In full ANSI Standard SQL youcan write row comparisons  (a,b,c) = (1,2,3) etc! but not in T-SQL dialect. Ignoring that problem, what you have is a design flaw called attribute splitting; you have put one unit of measurement
    in two columns. 
     I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the
    ISO-8601 data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00'
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • PreparedStatement wrapper behavior when SQLException is thrown

    Environment:
    weblogic8.1 sp3
    IBM db2 (universal) type 4 driver
    StatementCacheSize=0
    Use case:
    The code uses a PreparedStatement to insert let's say 60000 rows in a loop.
    The method used is executeUpdate() inside the loop. Some insertion
    attempts let's say 20000 are throwing duplicate primary key exception,
    which is fine. When such exception occurs it is skipped and the code
    continues with the next iteration inside the loop.
    Problem:
    Only one PreparedStatement is used in the code. Apparently the weblogic
    wrapper around the PreparedStatement is using a new wrapped
    PreparedStatement every time that a SQLException (in our case duplicate
    primary key) occurs when calling executeUpdate(). The result is that
    after ~7000 iterations in the loop (it's depend how much resources the
    database was allocated for the current session) the database throws another
    SQLException saying that there are no more memory resources for this
    session.
    Consequence:
    Memory consumption is extremely high – the loop cannot finish.
    I am guessing here: Every iteration in the loop that throws a SQLException
    causes the wrapper to use a new PreparedStatement which means execution
    of connection.prepareStatement() again – unnecessary roundtrip to the
    database.
    Note:
    The code was tested inside the weblogic container with different
    database MySQL - same behavior.
    The code work without any problems outside of the weblogic container and
    it uses only one object of type PreparedStatement.
    Thanks,
    Assen

    Assen Sotirov wrote:
    The code executes inside a POJO. Thus we can execute it as a standalone application or in EJB Session with CMP. There are only two differences:
    1) how a Connection is obtained - directly using the JDBC driver (standalone) or getting it from a DataSource (inside weblogic)
    2) how commit/rollback is done - directly using the Connection (standalone) or declare it in xml descriptor (inside weblogic)
    Connection pool definition:
    <JDBCConnectionPool
    Name="upsnd3db"
    DriverName="com.ibm.db2.jcc.DB2Driver"
    MaxCapacity="4"
    Password="{3DES}+BLABLABLABLABLA=="
    Properties="user=BLABLA"
    StatementCacheSize="0"
    StatementCacheType="LRU"
    Targets="pcs"
    URL="jdbc:db2://BLABLABLABLABLA:BLA/BLA"/>
    Turning the jdbc loggin on produces (IBM driver has rather verbose output, so I will truncate it):
    [Connection@b0c5a] prepareStatement (insert into ...) called
    [Connection@b0c5a] prepareStatement () returned PreparedStatement@b9979b
    [PreparedStatement@b9979b] setString (1, 00037NHD1 ) called
    [PreparedStatement@b9979b] setDate (2, 2005-09-01) called
    [PreparedStatement@b9979b] setTimestamp (9, 2005-09-15 15:26:12.093) called
    [PreparedStatement@b9979b] executeUpdate () called
    com.ibm.db2.jcc.c.SqlException
    ....at com.ibm.db2.jcc.c.cl.d(cl.java:1039)
    ....at com.ibm.db2.jcc.c.cm.executeUpdate(cm.java:311)
    ....at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:115)
    BEGIN TRACE_DIAGNOSTICS
    com.ibm.db2.jcc.c.SqlException:
    DB2 SQL error:
    SQLCODE: -803,
    SQLSTATE: 23505,
    [Connection@b0c5a] prepareStatement (insert into ...) called
    [Connection@b0c5a] prepareStatement () returned PreparedStatement@9830bc
    [PreparedStatement@9830bc] setString (1, 000759BA7 ) called
    Notice that the StatementCacheSize is 0 and also a new PreparedStatement is allocated and used after the SQLException is thrown. This contradict to your statement:
    I see, and I see something in the code. I have attached a
    patch to tey (get it ahead of the weblogic.jar in the
    server classspath).
    thanks
    Joe
    I am saying that for a zero-cache setup, the serverside statement wrapper
    won't change in any loop, and neither will the DBMS driver statement it
    wraps, regardless of any exceptions during execute() calls.Thanks,
    Assen

  • Can I use regular expression in JCR QueryBuilder?

    I want to find all the pages with cq:tag which end with "/testingtag"
    is it possible to do so using ?
    Are there any online tutorial on JCR QueryBuilder?
    I tried something like that but unfortunately it is not showing what I expected to see
    fulltext=testingtag$
    type=cq:tags

    Note that the querybuilder is a CQ (AEM) specific feature. A google search should give you what you want in the first search results: http://lmgtfy.com/?q=cq+querybuilder
    Now regarding your specific question: you want to use the property predicate with the like operation:
    property=cq:tags
    property.value=%/testingtag
    property.operation=like
    However, I don't see why you would want to search for all tags ending with a certain name. Tags must always be present under /etc/tags to be valid and so the logic would always be "let the user search/select some tags, and then search for that list specifically". Use the cq tagging API (javadocs) and also the querybuilder tag predicates (which are unfortunately not so well documented):
    tagid=some:tag/id
    tagid.property=jcr:content/cq:tags # to set a different property path; the default is cq:tags
    See also http://forums.adobe.com/message/4691188, http://forums.adobe.com/message/5223518 or https://www.sfu.ca/itservices/cms/howto/advanced/organize-and-optimize/advanced-queries.ht ml for some tagid predicate samples.

  • Can sql merge statement be used in a batch (oracle 10g)?

    Hello,
    I am trying to insert into an oracle table multiple rows of values selected from a web page. Can I use a merge statement as a preparedStatement to avoid inserting duplicate records?
    Does anybody have any examples they would like to share?
    Any suggestions are greatly appreciated.
    Thank you,
    Logan

    I've implemented this by batch inserting into a temp table then running a merge then dropping the temp table.
    public void mergeMethod() {
            final String createsql = "CREATE TABLE temp (a INTEGER, b INTEGER, c INTEGER)";
            final String insertsql = "INSERT INTO temp (a, b, c) VALUES (?,?,?)";
            final String mergesql = "MERGE INTO my_table A " +
               "USING temp B ON (A.a = B.a AND A.b = B.b) " +
               "WHEN MATCHED THEN UPDATE SET A.c = B.c " +
               "WHEN NOT MATCHED THEN INSERT (A.id, A.a, A.b, A.c) " +
               "VALUES (my_seq.Nextval,B.a,B.b,B.c)";
            final String dropsql = "DROP TABLE temp";
         Connection conn = null;
         Statement cs = null;
         Statement ms = null;
         Statement ds = null;
         PreparedStatement ps = null;
         boolean retValue = false;
         try {
              conn = getConnection();
              conn.setAutoCommit(false);
              cs = conn.createStatement();
              ms = conn.createStatement();
              ds = conn.createStatement();
              ps = conn.prepareStatement(insertsql);
              for (int i=0; i< 10; i++){
                   ps.setInt(1, i);
                   ps.setInt(2, i+1);
                   ps.setInt(3, i+2);
                   ps.addBatch();
              // create temp table
              cs.execute(createsql);
              // execute in batch
              final int updateCount[] = ps.executeBatch();
              // merge the two tables
              ms.execute(mergesql);
              // drop the temp table
              ds.execute(dropsql);
              conn.commit();
              System.out.println("Rows is updated: " + updateCount.length);
         } catch (final SQLException e) {
              if (conn != null) {
                  conn.rollback();
              throw e;
         } finally {
              if (ps != null) {
                  ps.close();
              if (cs != null) {
                  cs.close();
              if (ms != null) {
                  ms.close();
              if (ds != null) {
                  ds.close();
              if (conn != null) {
                  conn.close();
    }

  • Protocol Exception while using getGeneratedKeys() method

    Hi,
    I am getting the below Exception. I am using the Oracle Database 10.2.0.3. JDBC Driver ojdbc14.jar. This exception is thrown, when I am trying to use the getGeneratedKeys() method on the PreparedStatement. I used to get the Unsupported Exception, but after upgrading the Driver, I am getting this Error.
    java.sql.SQLException: Protocol violation
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:111)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:145)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:207)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:765)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:215)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:965)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1169)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3338)
    at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3444)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.execute(DelegatingPreparedStatement.java:169)
    I am able to run the same code on other remote machine, which contains the replica of the above database. Please help me to get the solution to the above exception. Thanks in advance

    Hello prasadmn,
    I am getting a similar issue with a customer using 10.2.0.3 and using ojdbc5.jar (Oracle JDBC Driver version - "11.1.0.7.0-Production")
    Did you need to upgrade as Ashok mentioned? Did that resolve your problem?
    I tried looking for the bug that Ashok mentioned but I could not find it anywhere.
    Any assistance or direction would be great.
    Thanks

  • How to use INSERT with no column name specified?

    I want to insert rows into a database table using JDBC's PreparedStatement. I want to specify all values for each row, so that in plain SQL I would not have to specify column names. I wonder if I can do same thing with JDBC in the same manner (it would save a lot of network traffic as far as I can understand)? The problem is:
    I need to know the data types of the columns to use correct setXXX method on my PreparedStatement. For example: ps.setString() for CHAR data and ps.setBytes() for binary data. I can use Connection.getMetadata().getColumns(..,..,tableName,'%') to get column types for all columns in my table as a ResultSet. However but I am not sure if I get them in the right order, i.e. in the order in which the columns have been defined for the table in CREATE TABLE.
    So it seems I have a tough choice: to get type information in order externally or to specify (and probably transfer via network) column names in each INSERT statement. :-(
    Do I have a better choice? Any ideas will be highly appreciated..

    ...if I get them in the right order, ....Only reason for that is if you are using a meta-data type solution. If you are then there is no solution. After all customer name and address are both just text. How could you tell which is first even if you had a way to handle the types?
    But if your inserts are fixed then try using varchars (single ticked entries.) This depends on the database/driver. If is supported then you will have to use SimpleDateFormat to format dates/times in the correct format for the database or use a prepared statement with bind variables.

Maybe you are looking for

  • Bluetooth no longer works for incoming calls after recent update

    When I updated my Bluetooth to iOS 6, the Bluetooth no longer works for incoming calls. I press button to answer call, it makes a small cracking noise, and then sends the call to my phone. I can use the Bluetooth for outgoing calls and it works just

  • How to disable options in ESS-Career and job-Skilla profile

    Hi All, In ESS-Career and Job-Skill profile,there are three are three buttons 1.EDIT SKILL,2.ADD NEW SKILL,3.DELETE SKILL. I want to disable those options in Skills profile. Can some body please help me in solving this. Thanks in advance. Regards, Th

  • Service Tax Condition Type.

    Hello All,               Can anyone please tell me which table can contain a field for tax condition type. In my PO when i click the invoices button i get the Taxes option in that i have two condition types , am not able to find them out. I tried KON

  • All I want to do is CRUD an Object to a Database

    I don't need security or transactions or XML marshalling or caching. I just want to CRUD! First I started with simple JDBC. Tables of tables of tables. Very tedious. Then I tried JAXB->XML->Oracle XML DB. A little bleeding edge. Vendor specific solut

  • To Kill Parent / Child process

    Hi , I'm facing problem with killing a process. I'm using "kill -9 <ppid>"(ppid - parent process id) command to kill the process, this command kills the parent process but the associated child process is not killed. I'm new to this Solaris, and my qu