REFCURSOR in getCursor CallableStatement

Hi ,
I am calling a stored package procedure which returns REFCursor (i am using oracle 8.1.6 as backend) throughjdbc
am importing the Oracle JDBC drivers which support bind variables of type REFCURSOR.(classes from the oracle.jdbc.driver package
8.1.7 driver)
Used the getCursor method of the CallableStatement to convert a REFCURSOR value returned by a PL/SQL block
into a ResultSet.
Casting the corresponding CallableStatement to oracle.jdbc.driver.OracleCallableStatement to use the getCursor method.
The problem is this works absolutely fine if i connect as the owner of the package procedure. but if i create a public syonym for the same package and grant execute
on package to other user.
And now if i connect as this other user through jdbc and run the same program it gives me SQLException
ora-00942 table or view does not exit.
(and the same thing works fine from sql*plus when the package is tested from thsi other) just to inform you that no grants / rights issues over here.
I am just unable to understand how do i proceed in this case, as no way i can have the package procedure being created in the same user, also doesn't sound
implementable in live environment.
Can any body confirm, if this is a bug in the dirver am using, and if so where do i find this
Please help me.
I hope i have given required info to get an answer.
Thanks. Geeta
null

I had the same problem. It only worked
for me if I granted both execute
permission on the Package as well as
select permission on the table accessed
by the package (which doesn't make sense)
null

Similar Messages

  • Using Refcursor in Callable Statement without using the Oracle Drivers

    Hello all,
    Is there anyway to have a stored procedure (Oracle 8i) return a refcursor to my CallableStatement without using the Oracle Thin drivers (i'm now using jdbcodbc). I've tried registering my out parameter with every possible type i can think of...REF, JAVA_OBJECT, OTHER, etc. but with no luck.
    Help!!!!

    Certainly...I connect to the database using the
    jdbcodbc driver and when i execute any of the code, i
    get the following error:
    java.sql.SQLException: [Oracle][ODBC][Ora]ORA-06550:
    line 1, column 7:
    PLS-00306: wrong number or types of arguments in call
    to 'PVISUAL_GET'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    It's bombing on the line that i attempt to register
    OracleTypes.CURSOR. It works fine when i use the
    oracle thin drivers, but i want to get this puppy
    working with the JdbcOdbcDriver. Here's the code:
    CallableStatement dbCall =
    nt dbCall =
    (CallableStatement)connection.prepareCall("{ call
    PAK_VISUAL_GET.pvisual_get(?, ?, ?, ?, ?, ?) }");
    dbCall.setString(1, sessionKey);
    dbCall.setInt(2,
    l.setInt(2, Integer.parseInt(storedVizID));
    dbCall.registerOutParameter(3,
    arameter(3, OracleTypes.CURSOR);
    dbCall.registerOutParameter(4,
    arameter(4, OracleTypes.NUMBER);
    dbCall.registerOutParameter(5,
    arameter(5, OracleTypes.VARCHAR);
    dbCall.registerOutParameter(6,
    arameter(6, OracleTypes.NUMBER);
    dbCall.execute();when you don't use oracle thin driver, you cannot use the OracleTypes. but, instead use the java.sql.Types values.Replace dbCall.registerOutParameter(3, OracleTypes.CURSOR); with
    dbCall.registerOutParameter(3,java.sql.Types.OTHER). things should be fine.
    Ganesh

  • CastCastException with OracleCallableStatement

    I'm trying to use Oracle JDBC extensions with the Oracle thin Driver (to
    read a cursor returned by a PL/SQL function). When I attempt to cast a
    CallableStatement to an weblogic.jdbc.vendor.oracle.OracleCallableStatement,
    the weblogic wrapper class, I still get the same ClassCastException as if I
    try to cast to a vanilla OracleCallableStatement. I thought the weblogic
    class was the fix to this problem.
    Code is:
    ResultSet rs =
    ((weblogic.jdbc.vendor.oracle.OracleCallableStatement)cs).getCursor(1);
    Exception is:
    java.sql.SQLException: java.lang.ClassCastException:
    oracle.jdbc.driver.OracleCallableStatement
    It's interesting that the exception is for
    oracle.jdbc.driver.CallableStatement, even though I'm casting to the
    Weblogic wrapper class.
    Weblogic version is 6.1 sp2
    Oracle is 8.1.6
    Does anyone know what's happeneng here, and how to fix it.
    Any help much appreciated
    John

    Unfortunatly, this doesn't work either - it doesn't understand the new type:
    java.sql.SQLException: Invalid column type
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:222)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:285)
    at
    oracle.jdbc.driver.OracleStatement.get_internal_type(OracleStatement.java:53
    40)
    at
    oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallab
    leStatement.java:245)
    at
    oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallab
    leStatement.java:370)
    at
    weblogic.jdbc.jts.Statement.registerOutParameter(Statement.java:973)
    at
    weblogic.jdbc.rmi.internal.CallableStatementImpl.registerOutParameter(Callab
    leStatementImpl.java:53)
    at
    weblogic.jdbc.rmi.SerialCallableStatement.registerOutParameter(SerialCallabl
    eStatement.java:48)
    at com.bluedot.beans.support.ProcedureBuffer.executeFunction(Unknown
    Source)
    at
    com.bluedot.beans.support.ProcedureBuffer.executeTagSetFunction(Unknown
    Source)
    at
    com.bluedot.beans.entityManagement.EntityManagementServerBean.getExhibitorSt
    ats(Unknown Source)
    at
    com.bluedot.beans.entityManagement.EntityManagementServerBean_7yjcm7_EOImpl.
    getExhibitorStats(EntityManagemen
    tServerBean_7yjcm7_EOImpl.java:37)
    etc
    "Slava Imeshev" <[email protected]> wrote in message
    news:[email protected]...
    OK. Now it's clear. You can not use OracleTypes.CURSOR.
    In order to get a result set from cursor, the right sequence
    should be following:
    cs.registerOutParameter(1, java.sql.Types.OTHER);
    cs.execute();
    ResultSet rs = cstmt.getResultSet(1);
    Regards,
    Slava Imeshev
    "John Prout" <[email protected]> wrote in message
    news:[email protected]...
    Slava
    Here's part of the stack trace - the whole thing is probably 100 lines:
    java.sql.SQLException: java.lang.ClassCastException:
    oracle.jdbc.driver.OracleCallableStatement
    at
    weblogic.jdbc.jts.CallableStatement.getCursor(CallableStatement.java:277)
    at
    weblogic.jdbc.rmi.internal.CallableStatementImpl.getCursor(CallableStatement
    Impl.java:420)
    at
    weblogic.jdbc.rmi.SerialCallableStatement.getCursor(SerialCallableStatement.
    java:496)
    at
    com.bluedot.beans.support.ProcedureBuffer.executeTagSetFunction(Unknown
    Source)
    at
    com.bluedot.beans.entityManagement.EntityManagementServerBean.getExhibitorSt
    ats(Unknown Source)
    at
    com.bluedot.beans.entityManagement.EntityManagementServerBean_7yjcm7_EOImpl.
    getExhibitorStats(EntityManagemen
    tServerBean_7yjcm7_EOImpl.java:421)
    at
    com.bluedot.beans.entityManagement.EntityManagementServerBean_7yjcm7_EOImpl_
    WLSkel.invoke(Unknown Source)
    at
    weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:296)
    As you can see, the PL/SQL code is being called from an EJB.
    The connection is obtained through JNDI:
    java.sql.Connection conn = null;
    Hashtable ht = new Hashtable() ;
    ht.put( Context.INITIAL_CONTEXT_FACTORY ,
    "weblogic.jndi.WLInitialContextFactory" );
    InitialContext ctx = new InitialContext( ht ) ;
    if ( ctx == null ) return null ;
    String dataSource = getUserSession().getDatabase() ;
    javax.sql.DataSource source = (javax.sql.DataSource) ctx.lookup(
    dataSource ) ;
    if ( source != null )
    conn = source.getConnection() ;
    Then the CallableStatement is obtained and used:
    OracleConnection con = null ;
    OracleCallableStatement cs = null ;
    Object returnValue = null;
    ResultSet rs = null ;
    // String in the form: { ? = call <procedure-name>[<arg1>,<arg2>,...]}
    StringBuffer buff = new StringBuffer();
    buff.append("{ ? = call ").append(functionName).append("()") ;
    // setup mStringBuffer and mStringLength so the rest of the class will
    work right
    buff.getChars(0, buff.length(),mStringBuffer,0);
    mStringLength = buff.length();
    con = (OracleConnection)psc.getDatabaseConnection() ;
    cs = (OracleCallableStatement)con.prepareCall( buff.toString() ) ;
    cs.registerOutParameter(1, OracleTypes.CURSOR);
    // printQuery( psc ) ;
    boolean result = cs.execute() ; // It's not in the API what "result"
    is...
    rs =
    ((weblogic.jdbc.vendor.oracle.OracleCallableStatement)cs).getCursor(1);
    The exception happens when I call getCursor(1)
    This code works outside weblogic, using a connection I obtain usingstandard
    JDBC and the Oracle thin driver.
    The sample is extracted from several pieces of the real code, so therecould
    be compile errors, etc
    John
    "Slava Imeshev" <[email protected]> wrote in message
    news:[email protected]...
    Hi John,
    Could you post the questionable code and the full exception?
    From information provided it's not clear whether this exception
    is thown from the server or from the app.
    Regards,
    Slava Imeshev
    "John Prout" <[email protected]> wrote in message
    news:[email protected]...
    I am getting a connection from a standard weblogic connection pool,
    using
    a
    JNDI lookup. I can see no way to directly obtain a
    weblogic.jdbc.vendor.oracle.OracleConnection. If I cast everything to
    the
    weblogic OracleConnection and OracleCallableStatement, I still get thesame
    ClassCastException
    Can you post an example of how to get the
    weblogic.jdbc.vendor.oracle.OracleConnection
    Thanks
    John
    "Slava Imeshev" <[email protected]> wrote in message
    news:[email protected]...
    Hi John,
    This exception is thrown because plain oracle connection was used.
    To use weblogic oracle extensions, connection should be obtained
    from the connection pool, either via DataSource or directly.
    Regards,
    Slava Imeshev
    "John Prout" <[email protected]> wrote in message
    news:[email protected]...
    I'm trying to use Oracle JDBC extensions with the Oracle thin Driver
    (to
    read a cursor returned by a PL/SQL function). When I attempt to cast a
    CallableStatement to anweblogic.jdbc.vendor.oracle.OracleCallableStatement,
    the weblogic wrapper class, I still get the same ClassCastException as
    if
    I
    try to cast to a vanilla OracleCallableStatement. I thought the
    weblogic
    class was the fix to this problem.
    Code is:
    ResultSet rs =
    ((weblogic.jdbc.vendor.oracle.OracleCallableStatement)cs).getCursor(1);
    >>>
    Exception is:
    java.sql.SQLException: java.lang.ClassCastException:
    oracle.jdbc.driver.OracleCallableStatement
    It's interesting that the exception is for
    oracle.jdbc.driver.CallableStatement, even though I'm casting to the
    Weblogic wrapper class.
    Weblogic version is 6.1 sp2
    Oracle is 8.1.6
    Does anyone know what's happeneng here, and how to fix it.
    Any help much appreciated
    John

  • How  to use  refcursor in a package

    i want to use refcursor in a package
    but when i am trying to declare a refcursor variable ,
    I get no error but the refcursor does not return anything .
    why is this happenning ?
    I also read that we cannot define cursor variables in a paclage .
    Then how to go about it ?
    regards
    shubhajit

    Since Oracle 7.3 REF CURSORS have been available which allow recordsets to be returned from stored procedures, functions and packages. The example below uses a ref cursor to return a subset of the records in the EMP table.
    First, a package definition is needed to hold the ref cursor type:
    CREATE OR REPLACE PACKAGE Types AS
    TYPE cursor_type IS REF CURSOR;
    END Types;
    Note. In Oracle9i the SYS_REFCURSOR type has been added making this first step unnecessary. If you are using Oracle9i or later simply ignore this first package and replace any references to Types.cursor_type with SYS_REFCURSOR.
    Next a procedure is defined to use the ref cursor:
    CREATE OR REPLACE
    PROCEDURE GetEmpRS (p_deptno IN emp.deptno%TYPE,
    p_recordset OUT Types.cursor_type) AS
    BEGIN
    OPEN p_recordset FOR
    SELECT ename,
    empno,
    deptno
    FROM emp
    WHERE deptno = p_deptno
    ORDER BY ename;
    END GetEmpRS;
    The resulting cursor can be referenced from PL/SQL as follows:
    SET SERVEROUTPUT ON SIZE 1000000
    DECLARE
    v_cursor Types.cursor_type;
    v_ename emp.ename%TYPE;
    v_empno emp.empno%TYPE;
    v_deptno emp.deptno%TYPE;
    BEGIN
    GetEmpRS (p_deptno => 30,
    p_recordset => v_cursor);
    LOOP
    FETCH v_cursor
    INTO v_ename, v_empno, v_deptno;
    EXIT WHEN v_cursor%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(v_ename || ' | ' || v_empno || ' | ' || v_deptno);
    END LOOP;
    CLOSE v_cursor;
    END;
    In addition the cursor can be used as an ADO Recordset:
    Dim conn, cmd, rs
    Set conn = Server.CreateObject("adodb.connection")
    conn.Open "DSN=TSH1;UID=scott;PWD=tiger"
    Set cmd = Server.CreateObject ("ADODB.Command")
    Set cmd.ActiveConnection = conn
    cmd.CommandText = "GetEmpRS"
    cmd.CommandType = 4 'adCmdStoredProc
    Dim param1
    Set param1 = cmd.CreateParameter ("deptno", adInteger, adParamInput)
    cmd.Parameters.Append param1
    param1.Value = 30
    Set rs = cmd.Execute
    Do Until rs.BOF Or rs.EOF
    -- Do something
    rs.MoveNext
    Loop
    rs.Close
    conn.Close
    Set rs = nothing
    Set param1 = nothing
    Set cmd = nothing
    Set conn = nothing
    The cursor can also be referenced as a Java ResultSet:
    import java.sql.*;
    import oracle.jdbc.*;
    public class TestResultSet {
    public TestResultSet() {
    try {
    DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
    Connection conn = DriverManager.getConnection("jdbc:oracle:oci:@w2k1", "scott", "tiger");
    CallableStatement stmt = conn.prepareCall("BEGIN GetEmpRS(?, ?); END;");
    stmt.setInt(1, 30); // DEPTNO
    stmt.registerOutParameter(2, OracleTypes.CURSOR); //REF CURSOR
    stmt.execute();
    ResultSet rs = ((OracleCallableStatement)stmt).getCursor(2);
    while (rs.next()) {
    System.out.println(rs.getString("ename") + ":" + rs.getString("empno") + ":" + rs.getString("deptno"));
    rs.close();
    rs = null;
    stmt.close();
    stmt = null;
    conn.close();
    conn = null;
    catch (SQLException e) {
    System.out.println(e.getLocalizedMessage());
    public static void main (String[] args) {
    new TestResultSet();
    Hope this helps. Regards
    Srini

  • Passing a RefCursor as a variable

    Hi,
    I was wondering if it is possible
    to pass a RefCursor/ResultSet as
    a variable. Basically in one class
    I would like to do this
    CallableStatement cstmt;
    ResultSet cursor = null;
    Connection sql_connect = null;
    sql_connect = connect();
    try
    cstmt = sql_connect.prepareCall
    ("begin open ? for select question
    from question; end;");
    cstmt.registerOutParameter(1,
    OracleTypes.CURSOR);
    cstmt.execute();
    cursor = ((OracleCallableStatement)
    cstmt).getCursor(1);
    } // end try
    and then pass "cursor" as a variable
    to another class to be processed.
    Is this possible?
    I have tried using a method which:
    ResultSet cursor = null;
    cursor = jum_sql.get_questions();
    but I am getting errors when I try to
    process it i.e.
    cursor.next()
    var = cursor.getString(1);
    Any help?
    Thanks so much for your help!!!
    Mike

    I have also been using cursors by typecasting it to ResultSet - I seem to have a different problem - I always get the 'max open cursors exceeded' error. the gist of the code is:
    I first open a cursor, get the data, for each record set retrieved, i create a statement, open a cursor, retrieve data, close cursor, close inside statement, and then iterate over the next recordset in the outer loop.
    I've been using Oracle thin driver on 8.1.7 with Weblogic 6.0 SP2 - any help would be appreciated
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Cliff Bailey ([email protected]):
    You have cursor defined as a ResultSet, but you're down casting an OracleCallableStatement:
    cursor = ((OracleCallableStatement)
    cstmt).getCursor(1);
    I think what you want to do is this:
    cursor = (java.sql.ResultSet)csmt.getObject(1); Then you can return the resultset.
    In anycase, I've had performance issues with this,and that's why I'm in this forum. If you get the x.getCursor to work and efficiently, let me know.<HR></BLOCKQUOTE>
    null

  • Error in calling Stored procedure returns REFCURSOR

    Hi,
    I've written a oracle stored procedure returning REFCURSOR. say,extractorderdespatchconfirmsp('','','','','','H1','ACG','','','','',:rc).
    Following statement throwing error.
    CallableStatement cs = con.PrepareCall("{extractorderdespatchconfirmsp('','','','','','H1','ACG','','','','',:rc)}");
    rs = cs.executeQuery();
    Could you rectify this problem and give me the currect code.
    riyaz

    Your naming convention leaves a little to be desired.
    String command = "{CALL extractorderdespatchconfirmsp(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}";
    CallableStatement cstmt = conn.prepareCall(command);
    //set the variables here ie, dates need to be a timestamp format. use set timestamp.
    cstmt.setInt(1, 2);
    cstmt.setString(2, "a string");
    cstmt.setInt(3, 0);
    //for return values
    cstmt.registerOutParameter(3, Types.INTEGER);
    cstmt.registerOutParameter(2, Types.INTEGER);
    cstmt.execute();
    int status = cstmt.getInt(3);
    int status2 = cstmt.getInt(2);
    cstmt.close();
    It took me awhile too to get JDBC to call these right.

  • Accessing a sys refcursor as a plsql out parameter

    The 11g jdbc guide gives and example of how to access a pl/sql function RETURNING a cursor. We have a stored proc that returns about 5 out parameters one of which is a SYS_REFCURSOR. This is different from RETURNING a ref cursor. Can someone please help me with how to pass a resultset object to the stored proc. I presume the same java declaration is required:
    ResultSet cursor;
    pass this as a parameter to the stored proc. I have listed the 11g JDBC sample code below:
    import oracle.jdbc.*;
    CallableStatement cstmt;
    ResultSet cursor;
    // Use a PL/SQL block to open the cursor
    ********** HIMANSHU reaplce this with the name of my stored proc dennis1.pkg_snapitall ****************
    cstmt = conn.prepareCall
    ("begin open ? for select ename from emp; end;");
    cstmt.registerOutParameter(1, OracleTypes.CURSOR);
    cstmt.execute();
    cursor = ((OracleCallableStatement)cstmt).getCursor(1);
    // Use the cursor like a standard ResultSet
    while (cursor.next ())
    {System.out.println (cursor.getString(1));}
    In the preceding example:
    •     A CallableStatement object is created by using the prepareCall method of the connection class.
    •     The callable statement implements a PL/SQL procedure that returns a REF CURSOR.
    •     As always, the output parameter of the callable statement must be registered to define its type. Use the type code OracleTypes.CURSOR for a REF CURSOR.
    •     The callable statement is run, returning the REF CURSOR.
    •     The CallableStatement object is cast to OracleCallableStatement to use the getCursor method, which is an Oracle extension to the standard JDBC API, and returns the REF CURSOR into a ResultSet object.

    public void readSysRef() throws SQLException {
    try {
    OracleCallableStatement stmt = (OracleCallableStatement)
    // both are ok.
    //NOTE: when using call, add ";" after get_empployees() will fail
    //connect.prepareCall("{ call ? := get_employees( ? ) }");
    connect.prepareCall("begin ? := get_employees( ? ); end;");
    stmt.registerOutParameter(1, OracleTypes.CURSOR);
    stmt.setInt( 2, 10000);
    stmt.execute();
    OracleResultSet rs = (OracleResultSet) stmt.getCursor(1);
    while (rs.next()) {
    System.out.format("Employee %1$s has salary %2$d.%n",
    rs.getString(1), rs.getInt(2));
    } catch (SQLException e) {
    throw e;
    }

  • ClassCastException casting CallableStatement to OracleCallableStatement

    Im trying to create a ViewObject based on a REF_CURSOR returned by PL/SQL stored procedure OUT parameter.
    I casted the normal CallableStatement to OracleCallableStatement so I can call the OracleCallableStatement.getCursor(index);
    CallableStatement statement = getDbTransaction.createCallableStatement(statementString, DbTransaction.DEFAULT);
    ResultSet rs = ((OracleCallableStatement)statement).getCursor(1);I get a "java.lang.ClassCastException: oracle_jdbc_driver_T4CCallableStatement_Proxy" when I run this piece of code.
    Jdeveloper version is Jdev10.1.3.1 Preview.
    regards,
    Anton

    I got a resolution for this. The reason for this exception is that I got the wrong import for the OracleCallableStatement. The correct import is "import oracle.jdbc.OracleCallableStatement" instead of "import oracle.jdbc.driver.OracleCallableStatement"
    See the related thread:
    Re: Dive into BC4J related  --REF CURSOR (executeQueryForCollection)
    regards,
    Anton

  • Gettig SQLException while using CallableStatement

    Hi,
    I am using Oracle 10 G JDBC Release 10.2.0.1.0 (ojdbc14.jar), I am getting SQLException while fetching next record from the resultset returned by a PLSQL procedure.The same code is working fine with classes12_g.jar
    Here is the code,
              CallableStatement cStat = null;
              PreparedStatement stat1 = null;
              Connection con = null;
              String decryptedPassword     =     null;
              boolean isPasswordExpiryDateValid     =     false;
              String message     =     "";
              boolean authenticated     =     false;
              boolean passwordExpired     =     false;
              HashMap hashMap     =     new HashMap();
              ResultSet callRs = null;
              try
                   con = getConnection();
                   cStat = con.prepareCall("{? = call passWd.decrypt_password(?, 'JPRAXISPASS')}");
                   cStat.registerOutParameter(1, java.sql.Types.VARCHAR);
                   cStat.setString(2, encryptedPassword);
                   callRs = cStat.executeQuery();
                   if(callRs.next())               {
                        decryptedPassword = cStat.getString(1);
    I am getting follwing SQLException
    java.sql.SQLException: Cannot perform fetch on a PLSQL statement: next is thrown when I try to fetch next record at line
    if(callRs.next())
    Please suggest the solution,
    Thanks and Regards,
    Rajendra Doulaghar

    Hi,
    First, execute() is recommended for CallableStatement.
    Second, with Oracle atabase, PL/SQL returns a Ref Cursor, not a result set; you need to invoke getCursor() on the returned object from PL/SQL to turn it into a result set then you cnatreat it as a regular result set.
    Kuassi, http://db360.blogspot.com/

  • Disadvantages of using REFCURSORs from JDBC

    Hi,
    Normally I write my SQL statements from inside Java (eg PreparedStatements).
    I am investigating on creating PL/SQL Packages, supplying procedures and methods, which I can call from Java using CallableStatements. I understand the advantages of having a layer/API on the database side.
    For example: retrieve some records from a table. (the PL/SQL function getCustomers returns a REFCURSOR)
    - PreparedStatement (select ... from ... where ...) -> executeQuery -> loop ResultSet
    - CallableStatement ("begin ? := getCustomers(); end;") -> cast getObject() to ResultSet -> loop ResultSet
    What are the disadvantages of using the CallableStatement (REFCURSOR)?
    Thanks, regards, Stephan

    While that article may be a good intro for someone not familiar with JDBC it has some misinformation in it that can be misleading at best and cause performance and memory issues at worst.
    Row-prefetching - there is little benefit to using a large value for this setting. As with most things extremes are to be avoided.
    It is important to know how the data is going to be used. What is the point of bringing ALL the data from the DB in one call if you are going to write it to the file system. File I/O is generally the slowest part of an application.
    It is also important that the code be scaleable. Apps should be written so that future modifications will impact existing functionality as little as possible. If you eat up the memory for one table or statement that limits the memory available for other uses. Worse, when things go wrong and you need to reduce the fetch setting you may now have problems everywhere because the testing you originally performed may have relied on that larger fetch setting.
    If the data fetching is not done in its own thread then using a very large value can actually make an application appear to 'freeze' while it waits for the data fetch to complete.
    A large fetch size can also waste significant amounts of memory; essentially allocating it but never using it and never allowing any other process to use it. This is because for a fetch size of 'n' Oracle has to allocate space for 'n' rows that are each of maximum size.
    This wasted is most often due to the common VARCHAR2 datatype. Consider a single column defined as VARCHAR2(100). In the DB this column is stored as variable length. But Oracle will allocate 100 characters (could be multi-byte characters) in order to be able to hold a maximum length value.
    If the actual data values never exceed 30 bytes then 70 bytes in each row are totally wasted. The more rows that are prefetched the more memory that is wasted simply in anticipation of a maximum length value that never occurs or only occurs rarely.
    I've never used a prefetch/fetch size greater than one thousand and that was for tables with small records (no more than 10 or 20 columns).
    And the Oracle docs don't even recommend a setting that high. See the JDBC Dev Guide
    http://docs.oracle.com/cd/B19306_01/java.102/b14355/oraperf.htm#i1043756
    >
    Oracle Row-Prefetching Limitations
    There is no maximum prefetch setting, but empirical evidence suggests that 10 is effective. Oracle has never observed a performance benefit to setting prefetch higher than 50. If you do not set the default row-prefetch value for a connection, then 10 is the default.

  • Return  a Refcursor

    Hi ,
    I need to write a procedure which return a multiple rows . This proc will be called by a java application . so my proc is like this
    create procedure trial(req_cursor out sys_refcursor) as
    emp_rec emp%rowtype
    begin
    open req_cursor for
    select * from emp where emp_id = xxx for update;
    loop
    fetch req_cursor into emp_rec ;
    exit when req_cursor%notfound;
    update emp_name = YY where emp_i d = emp_rec .emp_id;
    end loop;
    end;
    But from java when
    CallableStatement cst = dbConnection.prepareCall("{call trial(?)}");
    cst.registerOutParameter(1, OracleTypes.CURSOR);
    cst.execute();
    while(rst.next()){
              System.out.println(rst.getString("emp_name"));
    this ccode is throwing ORA-01002: fetch out of sequence
    I doubt in the procedure trial , am opening a refursor and loop it to do a update stmt . so the cursor is coming to an end and when i try to loop though cursor in java code it must be throwing . This is my assumptipn . But the code in my applicaion is exactly similar to what i have written above. And my requirement is after creating a refcursor i have to loop through it to change the status of a column . SO how can i get the rows ? Please suggest me a solution .
    If i dont loop in procedure then it is returning multiple rows which i can read in java app.
    Thanks in advance.

    user8690565 wrote:
    I am looping because before i pass the multiple rows back i want to change the status of a certain column so the same row is not read by any other thread.
    With out the above requirement it is staright forward that i can simple return the refcursor but i should update the rows selected and then return , thats the reason i posted this question in this forumYou definitely need to read the link I provided above. Your understanding of ref cursors (and cursors in general) is wrong.

  • ORA-01008 in CallableStatement

    It goes like this:
    String sqlStatement = "{ ? = call myFunction(?,?,?)}";
    CallableStatement cstmt = getConnection().prepareCall(sqlStatement);
    cstmt.registerOutParameter (1, OracleTypes.CURSOR);
    cstmt.setDate(1, new java.sql.Date(date.getTime()));
    cstmt.setInt(2, myIntegerParam1);
    cstmt.setInt(3, myIntegerParam2);
    cstmt.execute ();
    ResultSet cursor = ((OracleCallableStatement)cstmt).getCursor(1);
    while (cursor.next ()){
    res.add(cursor.getString(1));
    But I'm getting ORA-01008: not all variables bound. I suspect, that the first '?' is taken to be filled by setDate and so it's like 4 parameters I have instead of 3. What can be done? Any suggestions are welcome.

    I think that the out parameter has index 1 so the other three are 2,3,4. Please try this and post here whether it worked
    HTH
    Mike

  • Must I use OracleCallableStatement to process a REFCURSOR?

    Oracle 10g Rel 2 using latest Oracle thin drivers on a Java 1.5 application.
    I'm in the process of porting our existing application to Oracle, but for the next several months, I must support multiple databases (SQL Server, DB2) with the same codeline. Our db access layer is stored procs wrapped in CallableStatements whereby a vast majority returns a result set. I very much need to continue to use existing java.sql.CallableStatements and resultSets.
    A typical stored proc looks like this:
    CREATE OR REPLACE PROCEDURE getMeData
    v_c_columnname IN VARCHAR2 DEFAULT NULL ,
    v_intSort IN NUMBER DEFAULT 0 ,
    cv_1 IN OUT SYS_REFCURSOR
    AS
    BEGIN
    OPEN cv_1 FOR
    SELECT col1,
    col2,
    col3
    FROM someTable
    WHERE somecolumn = v_c_columnname ;
    END;
    We currently abstract the stored proc calls by doing a check on which db platform, then wrapping them with either EXEC or CALL and constructing the proc call for the target RDBMS.
    My first question is, is there a way for me to handle/process the return REFCURSOR in vanilla java.sql.Callable statement/ResultSets, or must I use oracle.jdbc.CallableStatment (and register the out cursor type (ie, cStmt.registerOutParameter(3, OracleTypes.CURSOR)?
    Second question - I'm currently testing with the OracleCallableStatement, but my cStmt.execute is simply skipping the execute call - I know its constructed properly, and when I call via pl/sql with binds, it returns properly, so am I missing something in how to process the REFCURSOR? It's not failing with an Oracle error, it's just not executing.
    This is the call:
    begin getMeData(?,?,?); end;
    Last question - must one use a REFCURSOR to return a result set via PL/SQL stored procs, or is there another way?
    TIA

    So, a bit confused. In the JDBC examples I've seen for refcursors, I see the following:
    CallableStatement stmt = connection.prepareCall("{? = call demo_refcursor.getRefCursor }");
    // Set the Out Parameter type to be of type CURSOR
    stmt.registerOutParameter(1, OracleTypes.CURSOR);
    stmt.execute(); // Execute the statement
    // Cast the returned parameter, (defined as type OracleTypes.CURSOR) to
    // a JDBC result-set.
    resultSet = (ResultSet)stmt.getObject(1);
    Where the call is in the format of {? = call myProc(?,?)}.
    Is the first ? (?= call) the registered out parameter? Am I understanding that correctly? If so, and my procedure looks something like this:
    CREATE OR REPLACE PROCEDURE getMeData
    v_c_columnname IN VARCHAR2 DEFAULT NULL ,
    v_intSort IN NUMBER DEFAULT 0 ,
    cv_1 IN OUT SYS_REFCURSOR
    AS
    BEGIN
    OPEN cv_1 FOR
    SELECT col1,
    col2,
    col3
    FROM someTable
    WHERE somecolumn = v_c_columnname ;
    END;
    ... where the refcursor is actually the third param, how do I make sure the ? = call is the refcursor param? Am I totally missing something here? I am a bit rusty, so forgive me if this is obvious and I'm just missing it..

  • Using CallableStatement.wasNull() after getObject()

    In our aplpication we are returning ResultSets from PL/SQL functions. We use CallableStatement.getObject()
    to return the ResultSet. After calling getObject we call wasNull() to make sure
    we did receive something.
    Originally we were using the jcbd thin driver provided by Oracle and our code
    ran fine. We had problems with that driver and switched to the OCI driver. The
    OCI driver does not like our code calling wasNull after getObject(). It throws
    and exception saying we have not called a getXXX method yet.
    The specification is kind of vague on this, it says wasNull can be called after
    any getXXX method. My question is, is there a problem with the OCI driver or
    is or code wrong?
    Below is a snippet of code that worked with the thin driver but not with the OCI
    driver:
    CallableStatement _stmt = null;
              int _arg = 1;
              try {
                   stmt = connection.prepareCall(GET_OTHER_PERFORMANCE_ASSETS_STMT);
                   stmt.registerOutParameter(arg++, sonymusic.util.JDBCHelper.SONYMUSIC_CURSOR);
                   if (inSiteId == null) {
                        stmt.setNull(arg++, java.sql.Types.BIGINT);
                   } else {
                        stmt.setLong(arg++, inSiteId.longValue());
                   if (inPerformanceId == null) {
                        stmt.setNull(arg++, java.sql.Types.BIGINT);
                   } else {
                        stmt.setLong(arg++, inPerformanceId.longValue());
                   if (authUserIdIn == null) {
                        stmt.setNull(arg++, java.sql.Types.BIGINT);
                   } else {
                        stmt.setLong(arg++, authUserIdIn.longValue());
                   _stmt.execute();
                   java.sql.ResultSet result = (java.sql.ResultSet)stmt.getObject(1);
                   if (_stmt.wasNull())
                        return null;
                   else
                        return _result;

    Hi Jeff,
    as mentioned in the spec, refereing to the doc you refered to earlier:
    You should be able to get the resultset first and then read the param on the
    resultset and then make a call to CallableStatement.wasNull to discover if
    the read returned a SQL "NULL". (if this value read from the resultset is a
    SQL "NULL" the wasNull() call will return a true).
    Hope this answers your questions here and clears up any confusion with the
    java null and, the SQL NULL that the wasNull call detects.
    getObject() is basically returning you what you asked it to return when you
    registered the out parameter.
    http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec/jdbc-spec.frame7.html
    7.3.2 Retrieving NULL values as OUT parameters
    As with ResultSets, in order to determine if a given OUT parameter value is
    SQL "NULL" you must first read the parameter and then use the
    CallableStatement.wasNull method to discover if the read returned a SQL
    "NULL".
    When you read a SQL "NULL" value using one of the CallableStatement.getXXX
    methods, you will receive a value of null, zero, or false, following the
    same rules specified in section 7.1.2 for the ResultSet.getXXX methods.
    sree
    "J Drost" <[email protected]> wrote in message
    news:[email protected]...
    >
    I am comfortable with a getXXX on available returning an empty result setif the
    pl/sql function itself returned an empty result set (if you do 'where 1 =0');
    Just as I am comfortable with a getInt invocation returning a 0 if thepl/sql
    function itself returned a 0. Or Course.
    I do however expect to be able to check wasNull on the CallableStatementafter
    getting a ResultSet from an out parameter. If the pl/sql function itselfdid
    not return a result set (it is possible in Oracle to simply not return avalue
    from a function), then I expect wasNull to return true.
    I would imaging that it is open to discussion what the getXXX shouldreturn if
    the database doesn't return anything. I would expect a null (after all Iam calling
    getObject, and you wouldn't expect the driver any other kind of emptyobject,
    so why an empty result set) but you could argue that an empty result setwould
    be acceptable. Regardless of that argument; if a function didn't returnthe result
    set, after the getXXX the wasNull should return true. Otherwise thedriver is
    hiding the actual results of the database call.
    Jeff
    "Sree Bodapati" <[email protected]> wrote:
    And I would like to add this note from 'Joe' here :
    "an empty result set is still a result set, not a null.
    Applications may well run queries that return no rows, but the
    application
    may still want the result set metadata, which is only available from
    the resultset. In fact some applications purposely execute queries
    with a clause like 'where 1 = 0' to ensure no rows are returned, but
    guarantee that they get the metadata."
    "Sree Bodapati" <[email protected]> wrote in message
    news:[email protected]...
    If you read through the same doc an little furture, They talk about
    resultsets,
    7.3.2 Retrieving NULL values as OUT parameters
    As with ResultSets, in order to determine if a given OUT parametervalue
    is
    SQL "NULL" you must first read the parameter and then use the
    CallableStatement.wasNull method to discover if the read returned aSQL
    "NULL".
    When you read a SQL "NULL" value using one of the
    CallableStatement.getXXX
    methods, you will receive a value of null, zero, or false, followingthe
    same rules specified in section 7.1.2 for the ResultSet.getXXX methods.
    hth
    sree
    "J Drost" <[email protected]> wrote in message
    news:[email protected]...
    Is their any explanation as to why a default value (an empty result
    set)
    is returned
    without setting the wasNull flag? This behavior seems to be
    inconsistent
    with
    the way other out parameters work. For example, when a function
    that is
    expected
    to return a number doesn't return a value, the default value (zero)
    is
    returned
    from the CallableStatement.getInt() method, but the wasNull flag
    is set
    to
    true.
    I don't know, it just doesn't seem consistent to me.
    Also, you are saying that if I have a pl/sql function that returns
    a
    REFCURSOR
    (a weakly typed cursor), and that function doesn't return a value,
    then
    the driver
    is going to create a ResultSet for me that contains no rows and has
    a
    ResultSetMetaData
    with a columnCount of zero? I would expect to get a java null based
    on
    what the
    spec, as well as they way other parameter types work.
    http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec/jdbc-spec.frame7.html
    7.1.2 Null result values
    * A Java "null" value for those getXXX methods that return Javaobjects.
    * A zero value for getByte, getShort, getInt, getLong, getFloat,and
    getDouble
    * A false value for getBoolean.
    "Sree Bodapati" <[email protected]> wrote:
    wasNull() checks to see if the last OUT param value is SQL NULL.
    if
    you
    have a CURSOR (ResultSet equivalent) as the OUT param then it willnot
    be
    SQL NULL if no results are returned.
    The Weblogic oci driver returns an empty resultset object in sucha
    case.
    I
    dont think it sets the wasNull() to return true in such a scenario.
    HTH
    Sree
    "Robert DeWilder" <robert@[email protected]> wrote in message
    news:[email protected]...
    In our aplpication we are returning ResultSets from PL/SQL
    functions.
    We
    use CallableStatement.getObject()
    to return the ResultSet. After calling getObject we call
    wasNull()
    to
    make sure
    we did receive something.
    Originally we were using the jcbd thin driver provided by Oracle
    and
    our
    code
    ran fine. We had problems with that driver and switched to the
    OCI
    driver. The
    OCI driver does not like our code calling wasNull after
    getObject().
    It
    throws
    and exception saying we have not called a getXXX method yet.
    The specification is kind of vague on this, it says wasNull can
    be
    called
    after
    any getXXX method. My question is, is there a problem with the
    OCI
    driver
    or
    is or code wrong?
    Below is a snippet of code that worked with the thin driver but
    not
    with
    the OCI
    driver:
    CallableStatement _stmt = null;
    int _arg = 1;
    try {
    _stmt =
    connection.prepareCall(GETOTHER_PERFORMANCE_ASSETS_STMT);
    stmt.registerOutParameter(arg++,sonymusic.util.JDBCHelper.SONYMUSIC_CURSOR);
    if (inSiteId == null) {
    stmt.setNull(arg++, java.sql.Types.BIGINT);
    } else {
    stmt.setLong(arg++, inSiteId.longValue());
    if (inPerformanceId == null) {
    stmt.setNull(arg++, java.sql.Types.BIGINT);
    } else {
    stmt.setLong(arg++, inPerformanceId.longValue());
    if (authUserIdIn == null) {
    stmt.setNull(arg++, java.sql.Types.BIGINT);
    } else {
    stmt.setLong(arg++, authUserIdIn.longValue());
    _stmt.execute();
    java.sql.ResultSet _result =
    (java.sql.ResultSet)_stmt.getObject(1);
    if (_stmt.wasNull())
    return null;
    else
    return _result;

  • Unable to execute an update statement using CallableStatement

    Hi there,
    I'm trying to run an update statement from JUnit using java.sql.CallableStatement and oracle.jbo.server.DBTransaction.
            String updateSql =
                "update footable set barcol=TO_DATE('12-SEP-09','dd-MM-yy') where bazcol = 505";
            try {
                statement =
                        applnModule.getDBTransaction().createCallableStatement(updateSql,
                                                                               2);
                int executeUpdate = statement.executeUpdate();
                AppsLogger.write(this,
                                 "# records UPDATED ------------------>" + executeUpdate,
                                 AppsLogger.SEVERE);
            } catch (SQLException s) {
                s.printStackTrace();
                Assert.fail("Encountered SQL Exception: " + s);
            } finally {
                try {
                    if (statement != null)
                        statement.close();
                } catch (SQLException s) {
            }Below is the exception I get when I run the above code. There is no problem with the SQL - it works fine from SQLDeveloper.
    java.lang.AssertionError: Encountered SQL Exception: java.sql.SQLDataException: ORA-01858: a non-numeric character was found where a numeric was expected
         org.junit.Assert.fail(Assert.java:91)
         sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         java.lang.reflect.Method.invoke(Method.java:597)
         org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
         org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:105)
         org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
         org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
         org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
         org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.invokeTestMethod(AtfJUnit4JTestCaseClassRunner.java:362)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.runMethods(AtfJUnit4JTestCaseClassRunner.java:272)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner$1.run(AtfJUnit4JTestCaseClassRunner.java:265)
         org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
         org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.run(AtfJUnit4JTestCaseClassRunner.java:262)Edited by: 911023 on Oct 2, 2012 11:28 AM
    Edited by: 911023 on Oct 2, 2012 11:30 AM

    Using case statement.
    UPDATE gor_gold_post
       SET hoov_flag = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 304
                                   OR
                                   (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END,
           b49n      = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 121.6
                             OR
                             (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END
    WHERE tariff_code IN (169, 135, 136);Note: Code not tested.

Maybe you are looking for

  • Error in Receiver Soap Adapter for Google API

    Hi, I am working on HTTP-XI-Soap scenario which on the receiver side calls google API for spell check. I get the following error : <b>No Deserializer found to deserialize a ':key' using encoding style 'http://schemas.xmlsoap.org/soap/encoding/'.</b>

  • How can I hide the marker button in an ALV GRID line?

    Hi all, I am switching an old program from ALV LIST to ALV GRID. In the old list, I put a checkbox on each line to abilify the user to mark some lines. However, there are some lines that I don't want the user to select. In the list, I set the field f

  • Portal Custom Search Results Question

    Hey, We are using a custom search portlet to search through a page group containing content relevant to a group of end users. The results generated from the search a fine apart from that they also return items from the page group such as navigation p

  • Database polling process

    I have created a bpel database polling process to process a single table and use a logical update (mark a column as processed). The table will contain many unprocessed records at any time. I have setup the polling interval 5 Sec and records unlimited

  • Run windows services from java application

    can java application run a windows server i have a web server that runing using tomcat and mysql can i make a icon in the systray that give me the option to (using a menu) run the server ,wicth means : tomcat and mysql are runing stop the server get