Resultset closing - technicality

"..... I declared Statement objects as class variables. You probably are doing the same. Doing this, you can't close the statements inside a method. (don't ask me why!!)
My solution was to declare those Statement objects inside the method where I execute and close the statements.
I think that will help you!!!"
I read this on a previous post but I am sceptical about whether this is true. I've declared resultsets as private class variables outside the method and closed them in the finally block of the method that uses them. Don't seem to cause any problems. Although I've not had the chance to check the v$open_cursor table.
Can anyone confirm if the statement above is true?

I believe declaring Statements outside the method is actually a good practice...especially if you are working with Oracle (I don't know about other databases, but I would imagine that they would behave the same way). In this case, you are actually reusing the same statement over and over again..which typically is good because it reduces the number of times Oracle parses your statement. If you declare the statement inside a method, you are doing the following:
1. You are creating a new object every time the method is invoked.
2. You are asking Oracle to parse your statement (which is quite expensive) every time the method is invoked. Note that even though you are executing the same statement, Oracle does a Soft parse (as against a hard parse).
3. Oracle opens a new cursor every time for the new Statement and you have to be very careful in closing the statement, else you will run out of Max Open Cursors.
hth
Kumar

Similar Messages

  • ResultSets Closing, cant use .last() etc

    I am filling 3 seperate resultsets using 3 seperate sql queries.
    The 1st query calls the connection classes setData() and passes in the sql statement, which connects, gets the data, puts it in a resultset, and returns it to the calling class. Then, the returned resultset copied into resultset1.
    The 2nd query then does the same thing, but its sql statement is getting different data from a different table, but it still uses the getData() method to do it. It then fills resultset2.
    Then the 3rd query runs its sql query the same way to fill resultset3.
    The problem is, after i have filled resultsets 1, 2 and 3, it wont let me call a .first() or .last() on any of them cause it says that the resultset is closed! Heres the exact error msg:
    "java.sql.SQLException: Operation not allowed after ResultSet closed"
    Heres the code where i try fill the 3 resultsets:
              mycon = new MysqlConnect();
                   details_res = mycon.getData("SELECT * FROM details ORDER BY details_id");     
                   details_res.last();
                   parts_res = mycon.getData("SELECT * FROM parts ORDER BY parts_id");               
                   parts_res.last();
                   costs_res = mycon.getData("SELECT * FROM costs ORDER BY costs_id");
                   costs_res.last();'mycon' is an object of the connection class.
    So im guessing that ive got a problem in the getData() method of the connection class so heres the code for that method:
         public ResultSet getData(String query)
              connect();
              try
                   // browseable in all directions, not sensitive to updates by other users, not updateable
                   stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // create empty SQL statement
                   // execute SQL query & store results
                   result = stmt.executeQuery(query);
                   con.close();        // close connection
                   System.out.println("Data Retrieved. Connection Closed");
              catch (SQLException e)
                   System.out.println("SQL Exception " + e);
              return result; // return the data
         }//end getData()'stmt' and 'con' are both declared at the top, private variables.

    Right. Exactly. This is the way it's supposed to be. You've got major fundamental flaws in your approach.
    First, the result set is not being copied, you're creating a new reference to it.
    Second, result sets AREN'T copied.
    Third, a ResultSet represents an arbitrarily large flow of data that will come throw the connection as you step through elements in the ResultSet; as soon as you close the connection, you cut off the flow.
    So the excpetion is exactly right, you've closed the flow and therefore can't move around in the ResultSet.

  • JDBC + MySQL : "Operation Not Allowed After ResultSet Closed"

    I have a very short piece of code. I use one connection to the database. I execute a query, get back a lot of rows, then iterate through the result set and for each row I get some information and then perform an insert into a different table.
    The problem is that the big result set I am iterating through keeps closing sometime during the first iteration. Why? I am using three different statements:
    1) Statement 1 is for the main query I want to iterate through
    2) Statement 2 is for a quick lookup I perform (on a different table) for each item in the iteration.
    3) Statement 3 is for the Insert statement which I perform for each item in the iteration. Again, I insert into a different table and I use "executeUpdate"
    Given the I have three different statements and I am working with three different tables, why does my main result set that I am iterating through keep closing on me?
    Here is the error I am getting:
    java.sql.SQLException: Operation not allowed after ResultSet closed
    at com.mysql.jdbc.ResultSet.checkClosed(ResultSet.java:3603)
    at com.mysql.jdbc.ResultSet.next(ResultSet.java:2468)
    at com.mysql.jdbc.UpdatableResultSet.next(UpdatableResultSet.java:565)
    Thanks for your help.

    I have a very short piece of code. I use one
    connection to the database. I execute a query, get
    back a lot of rows, then iterate through the result
    set and for each row I get some information and then
    perform an insert into a different table.Sounds like a classic case of making Java do what the database was made to do.
    I'd bet you can do this in a single INSERT with a SELECT in the database in one network roundtrip. The "quick lookup" might be a JOIN or a sub-SELECT. When you do a query, bring N rows back to the middle tier, then do an INSERT for each row that you retrieve it means (N+1) network roundtrips if you don't batch your INSERTs. I'd have a SQL expert give your code a look.
    The problem is that the big result set I am iterating
    through keeps closing sometime during the first
    iteration. Why? I am using three different
    statements:
    1) Statement 1 is for the main query I want to
    iterate through
    2) Statement 2 is for a quick lookup I perform (on a
    different table) for each item in the iteration.
    3) Statement 3 is for the Insert statement which I
    perform for each item in the iteration. Again, I
    insert into a different table and I use
    "executeUpdate"
    Given the I have three different statements and I am
    working with three different tables, why does my main
    result set that I am iterating through keep closing
    on me?Maybe your ResultSet or Statement goes out of scope. Do the Statements share a Connection?
    %

  • Want to know about the resultset closed exception

    hi,
    in my java programming, i have used two resultset objects.also two statement object have used.
    but the first resultset object is closed immediately after the second resultset object was created.
    then i have to use two resultset objects for my coding.
    what can i do?
    plzsnd me reply.

    You cannot have two result set simultaneously because you have only one cursor.
    To resolve this, you could store the data into a collection (a list form example) from the first result set that you close it. Then you open the second one and do your tasks using the collection.
    I think your problem could be resolved using PLSQL,
    hth

  • How could I Fix this problem .. ResultSet closed

    In my JSP page after 4or 5 refreshings i am getting an exeption either saying "Invalid state for getResultSet" of "ResultSet is closed". I'm not getting this if i refresh again. I've tried even by closing ResultSet, Statement and Connection objects at the end of page. Can u give me the solution

    This is correct, unless the guy is lucky enough to be using a driver that adheres to JDBC 3. Try unloading the ResultSet object into a cache and then referencing that on subsequent calls to the page, (unless data staleness is an issue). You'd probably find it useful to browse some of the data transfer patterns to understand the deeper issues in what you're doing.

  • Mysterious closing ResultSets

    I'm getting desperate for a solution to this problem (as is the rest of the development team!).
    Basically we've been trying to create a system that automatically assigns values (frequencies) to objects (nodes) based on a rule set. Each node contains a varying number of sub-objects (radios) and each radio needs one frequency. The database has been set up and has test data for our Solution class to go through. However, we've run into an odd problem where our ResultSets are suddenly closing.
    The classes work like this:
    Database Broker (handles connection to DB, as well as executeQuery and executeUpdate statements.)
    Entry Broker (Holds all SQL statements for data retrieval in various methods. Each method contains an SQL statement to access data, and code to format that data into something useable by the main class.
    Solution/Main class (Contains methods to use the data from the Entry Broker to test valid solutions. Certain rules apply to assigning frequencies to radios and this class ensures that the data applies to these rules before it writes the data back to the DB (via the EntryBroker).
    The problem we continually run into is that whilst the ResultSets work fine in the Entry Broker, they are closed when they return to the Main class.
    Here's the catch: It seems in most cases that only the FIRST ResultSet returned in each method is closed, the remaining ResultSets work fine. We worked around this problem by creating a 'dummy' ResultSet, which obtained data from the database which was never used (the project name). We put this in its own try catch bracket so it would not interrupt the project.
    It worked fine for a few classes, but for others (notably the following one) it was ineffective. We've searched and searched but we cannot find anyone with a similar complaint (except a few people who have commented about ODBC version problems). Our ODBC version is 3.520.7713.0
    Here's an example method from the Solution class (The entire class is over 1000 lines):
    // Method to test Harmonic resonance for nodes within 10m
    private boolean resonanceGlobal (boolean tstResonanceG, double txFreq, double rxFreq, int distance)     {
    System.out.println("Beginning global harmonic resonance check");
    try {
    // Getting Nodes
    rsNode2 = eBroker.getNodes(projectNo);
    // node loop
    while (rsNode2.next())     {
    System.out.println("602 Test Marker GHarm 1");
    // get next node, store in nodeTemp
    nodeTemp = rsNode2.getInt(1);
    // System out to show which nodes will pass if statement
    System.out.println(node + " compare to " + nodeTemp);
    // avoid testing the same node against itself
    if (nodeTemp != node)     {
    // distance check (only neccesary within 10m)
    System.out.println("Test Marker Before Distance check");
    distance = getDistance(node, nodeTemp, distance);
    System.out.println("Test Marker After Distance check");
    // distance check if statement
    if (distance <= 10)     {
    System.out.println("618 Test Marker GHarm 2");
    // get the radios of the node, foreign node
    rsRadiosTemp = eBroker.getRadios(node);
    rsDummy = eBroker.getDummy(projectNo);
    rsRadios2 = eBroker.getRadios(nodeTemp);
    // This dummy ResultSet normally fails so that
    // the other ResultSets perform normally
    try {
    rsDummy.next();
    }     // end try
    catch (java.sql.SQLException dummyException)     {
    System.out.println("dummyException " + dummyException);
    }     // end catch
    // radio loop
    while (rsRadiosTemp.next())     {     // error occurs here
    System.out.println("627 Test Marker GHarm 3");
    // loop for foreign node radios
    while (rsRadios2.next())     {
    System.out.println("631 Test Marker GHarm 4");
    // get next radio
    radioTemp = rsRadios2.getInt(1);
    // get the TX and RX of the radio
    genericTX = getTX(radioTemp);
    radioTempCon = getConnection(radioTemp);
    genericRX = getTX(radioTempCon);
    // calculate bounds for harmonics test
    txLo = ((txFreq * 2) - genericTX) - 4;     // 4Mhz below TX harmonics check
    txHi = ((txFreq * 2) - genericTX) + 4;     // 4Mhz above TX harmonics check
    rxHi = ((rxFreq * 2) - genericRX) + 4;     // 4Mhz above RX harmonics check
    rxLo = ((rxFreq * 2) - genericRX) - 4;     // 4Mhz below RX harmonics check
    // checks TX and RX of foreign radio against TX, RX of current radio for separation
    if ((txLo > genericTX && txHi < genericTX) || (rxLo > genericRX && rxHi < genericRX))     {
    tstResonanceG = false;     
    break;
    } //end if
    else {
    tstResonanceG = true;
    }     // end else
    } //end foreign radio loop
    // breaking out of loops for return
    if (tstResonanceG == false)
    break;
    }     // end radio loop
    rsRadios2.close();
    rsRadiosTemp.close();
    }     // end sameradio check
    }     // end distance check
    }// end node loop
    rsNode2.close();
    }     // end try
    // Catch statement to stop from crashing in the
    // event of an error during SQL statements.
    catch (java.sql.SQLException resonanceGlobalException) {
    // Prints out the error message produced
    System.out.println(resonanceGlobalException);
    }     // end catch
    // returns result
    return tstResonanceG;
    } //end checkHarmonicResonanceGlobal()
    My apologies if it is a little hard to read, but the indenting is accurate. The Entry Broker methods which this method uses are here:
    public ResultSet getNodes (int projectNo) {
    // creating SQL statement
    sqlStatement = "SELECT nodeNo from tblNode WHERE projectNo = " + projectNo;
    System.out.println(sqlStatement);
    // executing SQL statement
    rsNodes = db.runQuery(sqlStatement);
    // returns ResultSet
    return rsNodes;
    }     // end getNodes
    // Method to get the distance between any two nodes
    public int getDistance (int projectNo, int node, int tempNode)     {
    ResultSet rsX1;                         // Used for obtaining the X-coord of node 1
    ResultSet rsX2;                         // Used for obtaining the X-coord of node 2
    ResultSet rsY1;                         // Used for obtaining the Y-coord of node 1
    ResultSet rsY2;                         // Used for obtaining the Y-coord of node 2
    double distance = 0;                    // Used in Global checks
    int dist = 0;                              // Used in Global checks
    int x1 = 0;                                   // Used in calculating distance
    int x2 = 0;                                   // Used in calculating distance
    int y1 = 0;                                   // Used in calculating distance
    int y2 = 0;                                   // Used in calculating distance
    int xDist = 0;                              // Used in calculating distance
    int yDist = 0;                              // Used in calculating distance
    int distint = 0;                         // Used to store converted values
    try {
    // get the X and Y co-ordinates of both nodes
    sqlStatement = "SELECT xCoord FROM tblNode WHERE nodeNo = " + node + " AND projectNo = " + projectNo;
    rsX1 = db.runQuery(sqlStatement);
    rsX1.next();
    x1 = rsX1.getInt(1);
    sqlStatement = "SELECT yCoord FROM tblNode WHERE nodeNo = " + node + " AND projectNo = " + projectNo;
    rsY1 = db.runQuery(sqlStatement);
    rsY1.next();
    y1 = rsY1.getInt(1);
    sqlStatement = "SELECT xCoord FROM tblNode WHERE nodeNo = " + tempNode + " AND projectNo = " + projectNo;
    rsX2 = db.runQuery(sqlStatement);
    rsX2.next();
    x2 = rsX2.getInt(1);
    sqlStatement = "SELECT yCoord FROM tblNode WHERE nodeNo = " + tempNode + " AND projectNo = " + projectNo;
    rsY2 = db.runQuery(sqlStatement);
    rsY2.next();
    y2 = rsY2.getInt(1);
    }     // end try
    catch (java.sql.SQLException getDistanceException) {
    System.out.println(getDistanceException);
    // calculating distance
    yDist = y2 - y1;
    xDist = x2 - x1;
    // perform pythagoras theorem for distance
    dist = (xDist * xDist) + (yDist * yDist);
    distance = java.lang.Math.sqrt(dist);
    Double roundFreqTemp = new Double(freqTemp);
    distint = roundFreqTemp.intValue() ;
    return distint;
    } // end get distance method
    // Method to get all the radios in a node
    public ResultSet getRadios(int node)     {
    ResultSet rsRadios;          // Used for obtaining radios in a node
    // creating sql Statement
    sqlStatement = "SELECT * FROM tblRadio WHERE nodeNo =" + node;
    System.out.println(sqlStatement);
    // executing sql Statement
    rsRadios = db.runQuery(sqlStatement);
    System.out.println("EB Test Marker 1: Line 261");
    // returning radio no
    return rsRadios;
    }//end getRadio
    public double getTX(int radioTemp){
    double txTemp = 0;     // Used for storing TX of a radio
    int freqNoTemp = 0; // Used for storing the frequency ID
    rsDummy = getDummy(projectNo);
    // creating SQL statement
    sqlStatement ="Select frequencyNo from tblRadio where radioNo = " + radioTemp;
    System.out.println(sqlStatement);
    // executing SQL statement
    rsTX = db.runQuery(sqlStatement);
    try {
    System.out.println("Test Marker EB1: 317");
    try {
    rsDummy.next();
    }     // end try
    catch     (java.sql.SQLException dummyException)     {
    System.out.println("dummyException" + dummyException);
    }     // end catch
    System.out.println("Test MarkerEB2: 330");
    // moving to first position in rs
    rsTX.next();
    System.out.println("Test MarkerEB3: 334");
    // obtaining data from rs
    freqNoTemp = rsTX.getInt(1);
    System.out.println("Test MarkerEB4: 337");
    rsTX.close();
    }     // end try
    catch (java.sql.SQLException rsTXException)     {
    System.out.println("rsTXExeption: " + rsTXException);
    }     // emd catch
    System.out.println("Frequency No is: " + freqNoTemp);
    rsDummy = getDummy(projectNo);
    sqlStatement = "Select frequency from tblFreq where frequencyNo = " + freqNoTemp;
    System.out.println(sqlStatement);
    rsRX = db.runQuery(sqlStatement);
    try {
    try {
    System.out.println("Test MarkerEB6: 361");
    rsDummy.next();
    }     // end try
    catch     (java.sql.SQLException dummyException)     {
    System.out.println("dummyException" + dummyException);
    }     // end catch
    System.out.println("Test MarkerEB5: 373");
    rsRX.next();
    System.out.println("Test MarkerEB7: 376");
    txTemp = rsRX.getDouble(1);
    System.out.println("Test MarkerEB8: 379");
    rsRX.close();
    }     // end try
    catch (java.sql.SQLException rxException) {
    System.out.println("rxException " + rxException);
    } // end catch
         System.out.println("393 Before return");
    return txTemp;
    }     //end getTX
    public int getConnection(int radio) {
    int nodeCon = 0;                    // Used to return the connected node no
    ResultSet rsConnection;          // Used for obtaining the foreign radio
    // creating SQL statement
    sqlStatement = "SELECT radioNo FROM tblRadio where recRadio = " + radio;
    System.out.println(sqlStatement);
    // executing SQL statement
    rsConnection = db.runQuery(sqlStatement);
    try {
    // moving to first position in rs
    rsConnection.next();
    // obtaining data from rs
    nodeCon = rsConnection.getInt(1);
    }     // end try
    catch (java.sql.SQLException getConnectionException) {
    System.out.println("getConnectionException : " + getConnectionException);
    }     // end catch
    // returns node no.
    return nodeCon;
    And finally, the dummy rs:
    // Dummy method to fix resultSet closed error
    public ResultSet getDummy (int projectNo) {
    sqlStatement = "Select projectName from tblProject where projectNo = " + projectNo;
    System.out.println(sqlStatement);
    rsDummy = db.runQuery(sqlStatement);
    return rsDummy;
    Here is some sample output that we have:
    ----jGRASP exec: java MainGui
    slider value constructor: 50
    116: if(singleton==null) {
    120: singleton=new Resolvotron
    Connection to D/Base establised
    Select projectName from tblProject where projectNo = 3
    Init OK. Beginning solve process
    main OK: beginning frequency assign process
    SELECT nodeNo from tblNode WHERE projectNo = 3
    267: Node number = 2
    SELECT * FROM tblRadio WHERE nodeNo =2
    EB Test Marker 1: Line 261
    Test Marker 1: Line 289
    298: Radio number = 4
    Test Marker 5: Line 308
    Test Marker 3: Line 313
    SELECT frequency from tblFreq WHERE projectNo = 3
    125.5
    Beginning test process
    Test Marker 4: Line 386
    Beginning check 257072
    Test Marker 6: Line 774
    70 Mhz Margin = false
    Beginning local 10Mhz separation check
    SELECT * FROM tblRadio WHERE nodeNo =2
    EB Test Marker 1: Line 261
    Getting TX of radio: 4
    Select projectName from tblProject where projectNo = 3
    Select frequencyNo from tblRadio where radioNo = 4
    Test Marker EB1: 317
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB2: 330
    Test MarkerEB3: 334
    Test MarkerEB4: 337
    Frequency No is: 2
    Select projectName from tblProject where projectNo = 3
    Select frequency from tblFreq where frequencyNo = 2
    Test MarkerEB6: 361
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB5: 373
    Test MarkerEB7: 376
    Test MarkerEB8: 379
    393 Before return
    432: getting connection
    SELECT radioNo FROM tblRadio where recRadio = 4
    438: getting TX of radio: 6
    Select projectName from tblProject where projectNo = 3
    Select frequencyNo from tblRadio where radioNo = 6
    Test Marker EB1: 317
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB2: 330
    Test MarkerEB3: 334
    Test MarkerEB4: 337
    Frequency No is: 2
    Select projectName from tblProject where projectNo = 3
    Select frequency from tblFreq where frequencyNo = 2
    Test MarkerEB6: 361
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB5: 373
    Test MarkerEB7: 376
    Test MarkerEB8: 379
    393 Before return
    java.sql.SQLException: ResultSet is closed
    10 Mhz Local = true
    Beginning 10 Mhz separation check
    SELECT nodeNo from tblNode WHERE projectNo = 3
    Node number is 2
    10 Mhz Global = false
    Beginning local harmonic resonance check
    SELECT * FROM tblRadio WHERE nodeNo =2
    EB Test Marker 1: Line 261
    Select projectName from tblProject where projectNo = 3
    Select frequencyNo from tblRadio where radioNo = 4
    Test Marker EB1: 317
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB2: 330
    Test MarkerEB3: 334
    Test MarkerEB4: 337
    Frequency No is: 2
    Select projectName from tblProject where projectNo = 3
    Select frequency from tblFreq where frequencyNo = 2
    Test MarkerEB6: 361
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB5: 373
    Test MarkerEB7: 376
    Test MarkerEB8: 379
    393 Before return
    SELECT radioNo FROM tblRadio where recRadio = 4
    Select projectName from tblProject where projectNo = 3
    Select frequencyNo from tblRadio where radioNo = 6
    Test Marker EB1: 317
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB2: 330
    Test MarkerEB3: 334
    Test MarkerEB4: 337
    Frequency No is: 2
    Select projectName from tblProject where projectNo = 3
    Select frequency from tblFreq where frequencyNo = 2
    Test MarkerEB6: 361
    I'll leave it at that, since the program goes into an endless loop. The dummy Exceptions are our dummy resultsets crashing so the rest can survive. The other stuff is from different methods. You should be able to locate the logic of the program by following the System.outs
    Test Markers with EB refer to the Entry Broker.
    Any help would be appreciated since we cannot find any other way of running this class successfully.
    Steve

    Ok problem solved...
    Basically I was calling one ResultSet after another. Thanks to the Database Broker's structure, this was killing the first ResultSet. I fixed up the loops so that ResultSets were only ever called just before they were needed, and it fixed the problem. The only other errors were simple logic faults which I drummed out in short order. Thanks for the help everyone!

  • Statement.close() Not closing the Result set

    Hi all,
    I have the following code which invokes a procedure in Oracle database
    public static callProcedure(Connection connection,String procedure){
    ResultSet resultSet = null;
    CallableStatement callableStatement = null;
    try {
    callableStatement = connection.prepareCall(procedure);
    callableStatement.registerOutParameter(1,OracleTypes.CURSOR);
    callableStatement.execute();
    resultSet =((OracleCallableStatement)callableStatement).getCursor(1);
    } catch (Exception exception) {
    exception.printStackTrace();
    } finally {
    try {
    callableStatement.close();
    } catch (SQLException sqlException) {
    sqlException.printStackTrace()
    return resultSet;
    Ideally if i try to iterate through the result set which is returned then it should give me resultset closed as i am closing the resultset. But this is not happening.
    Please anybody can explain the isue

    Hi,
    That is not easy to explain, I might take a guess and say that a statement cache is being used therefore the statement is not actually being closed.
    I always close the reultset then the statement so wouldn't notice this behaviour.
    Why are you returning a resultset anyway? If you really need to do this I would suggest using a disconnected resultset:
    OracleCachedRowSet ocrs = new OracleCachedRowSet();
    ocrs.populate(resultSet);
    return ocrs;

  • One Statement - Many ResultSets??

    Hey Folks,
    how good of an idea is it to use just one DB Statement and than make many queries on it ending up in different resultsets:
    Like this:
    try
                   Class.forName("com.mysql.jdbc.Driver").newInstance ();
                   con = DriverManager.getConnection (url, benutzer, passwort);
                   stmt = verbindung.createStatement();
              catch (Exception e)
                   e.printStackTrace();
    ResultSet rs7 = null;          
              try {
                   rs7 = stmt.executeQuery("SELECT * FROM artikel WHERE `artikel_nr` = " + artikelnr);
                   while ( rs7.next() ) {
                        level = rs7.getInt("persopreislevel");
              } catch (SQLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    rs7.close();
    ResultSet rs8 = null;          
              try {
                   rs8 = stmt.executeQuery("SELECT * FROM artikel WHERE `artikel_nr` = " + artikelnr);
                   while ( rs8.next() ) {
                        level = rs8.getInt("persopreislevel");
              } catch (SQLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    rs8.close();Or would I have to create one Statement per ResultSet?? How do I avoid creating to many Objects??
    My Problem is that i get NoOperationAllowed after ResultSet closed Errors once in a while, even though I am using different Resultsets but JDBC Api says 1 ResultSet per Statement right?
    Best regards
    Edited by: eCashier on Apr 1, 2008 7:26 AM

    Why not use a prepared statement and then a loop iterating through the parameters that you want to supply to the query instead of hardcoding eight queries that do essentially the same thing?
    But no, there's no profound overhead from opening multiple resultsets in sequence as long as you close them when you're done with them. You should close them in a finally block. The overhead from the result set objects is unlikely to be significant as long as they're closed.

  • Invalid Cursor state Exception  -  Help required

    Hi,
    I'm having a web page(JSP), which is making use of 3 ResultSet objects. Using the first two, i'll populate two different Drop down list, with values from database(Access) while loading the page for first time.
    Now if the user select any value from any (or both) of drop down list and clicks submit, i need to display all values in database, meeting the criteria from first & second drop down list. For this selection, i'm using the third ResultSet variable. While executing the query, i'm sure that 3rd ResultSet is returning some value. But when i try to retrieve the value to a string variable, i'm getting the Invalid cursor state exception.
    Throughout the page, i haven't closed any of the ResultSet. When i closed the first and second ResultSets in the third function(where 3rd ResultSet is used), i'm not getting any value. Its returning like ResultSet closed.
    Please help me to get this solved. It's very urgent because without this, i cannot proceed further. Please share your ideas.
    Thanks in advace for your valuable help

    If you open a new resultset within the same statement, all previously opened will be closed.
    Read the API docs, luke.

  • Problem with XSU when trying to execute pl/sql package returning ref cursor

    Hi,
    I'm exploring xsu with 8i database.
    I tried running sample program which I took from oracle
    documentation. Here is the details of these.
    ------create package returning ref cursor---
    CREATE OR REPLACE package testRef is
         Type empRef IS REF CURSOR;
         function testRefCur return empRef;
    End;
    CREATE OR REPLACE package body testRef is
    function testRefCur RETURN empREF is
    a empREF;
    begin
    OPEN a FOR select * from emp;
    return a;
    end;
    end;
    ---------package successfully created-----
    Now I use java program to generate xml data from ref cursor
    ------------java program ----------
    import org.w3c.dom.*;
    import oracle.xml.parser.v2.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.xml.sql.query.OracleXMLQuery;
    import java.io.*;
    public class REFCURt
    public static void main(String[] argv)
    throws SQLException
    String str = null;
    Connection conn = getConnection("scott","tiger"); //
    create connection
    // Create a ResultSet object by calling the PL/SQL function
    CallableStatement stmt =
    conn.prepareCall("begin ? := testRef.testRefCur();
    end;");
    stmt.registerOutParameter(1,OracleTypes.CURSOR); // set
    the define type
    stmt.execute(); // Execute the statement.
    ResultSet rset = (ResultSet)stmt.getObject(1); // Get the
    ResultSet
    OracleXMLQuery qry = new OracleXMLQuery(conn,rset); //
    prepare Query class
         try
    qry.setRaiseNoRowsException(true);
    qry.setRaiseException(true);
    qry.keepCursorState(true); // set options (keep the
    cursor alive..
         System.out.println("..before printing...");
    while ((str = qry.getXMLString())!= null)
    System.out.println(str);
         catch(oracle.xml.sql.OracleXMLSQLNoRowsException ex)
    System.out.println(" END OF OUTPUT ");
    qry.close(); // close the query..!
    // qry.close(); // close the query..!
    // Note since we supplied the statement and resultset,
    closing the
    // OracleXMLquery instance will not close these. We would
    need to
    // explicitly close this ourselves..!
    stmt.close();
    conn.close();
    // Get the connection given the user name and password..!
    private static Connection getConnection(String user, String
    passwd)
    throws SQLException
    DriverManager.registerDriver(new
    oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection
    ("jdbc:oracle:thin:@xxxx:1521:yyyy",user,passwd);
    return conn;
    when I ran the program after successful compilation,I got the
    following error
    ==========
    Exception in thread "main" oracle.xml.sql.OracleXMLSQLException:
    1
    at oracle.xml.sql.core.OracleXMLConvert.getXML(Compiled
    Code)
    at oracle.xml.sql.query.OracleXMLQuery.getXMLString
    (OracleXMLQuery.java:263)
    at oracle.xml.sql.query.OracleXMLQuery.getXMLString
    (OracleXMLQuery.java:217)
    at oracle.xml.sql.query.OracleXMLQuery.getXMLString
    (OracleXMLQuery.java:194)
    at REFCURt.main(Compiled Code)
    ============================
    Can anybody tell me why I'm getting this error.Am I missing any
    settings?
    thanks

    We are using 8.1.7 Oracle db with latest xdk loaded.
    am I missing any settings?

  • Exception Handling-rite way??

    Hi Friends,
    This Exception handling is really causing some problems for me.I run a query,return the resultset,cook the data from my other java class and display it thru my jsp and the last statement from my jsp is to call the close method(commented out).The problem is if some unknown Exception arises the close() method is not being called,causing open connections which later on are
    creating some disasters.I tried to implement it now using the finally method,so that it always gets closed,but hte problem is when i call the ReturnResultSet() method and try to cook the data,it says "ResultSet Closed".Please tell me which is the right way to implement this:
    public ResultSet ReturnResultSet(String Query) throws Exception
         try{  
           if (datasource != null) {
             connection = datasource.getConnection();
             if (connection != null) {
               statement = connection.createStatement( );
               resultset = statement.executeQuery(Query);         
           return resultset;
         } catch (SQLException sqle)
           sqle.printStackTrace();
           return null;
         finally {       
         try {
           if (resultset != null) resultset.close();
           if (statement != null) statement.close();
           if (connection != null) connection.close();
         catch (SQLException sqle) {
           sqle.printStackTrace();
    public void close()
       try { resultset.close(); } catch (Exception ex) {}
       try { statement.close(); } catch (Exception ex) {}
       try { connection.close(); } catch (Exception ex) {}
    */Any help would be appreciated and some duke dollars would be awarded too.Thanks

    Ok I think i got your point and i should award you
    the duke dollars too,but one last thing to ask.I call
    the close() method after all my processing is over,I
    just
    wanna know should I have the connection.close() thing
    inside it,becuase dont that contradicts the whole
    connection pool thing,as i am closing a connection
    and it has to open a new connection for every
    request.Or should i just have resultset.close() and
    statement.close() in it.
    Thanks for all your helpAre you talking about a standard J2EE container-provided connection pool? If so, then yes, you still need to 'close' the connection. That doesn't actually close it, it just tells the pool it is available to be used again the next time someone asks it for a connection. Hopefully you're not writing your own home-grown "connection pool".

  • Connection authentication error occured

    Hi, i'm using netbeans 6.8 and java DB ClientDriver.I want to insert data into database table, so after inserting data into required fields and by clicking on submit button it is displaying the message as :Connection authentication failure occurred. Reason: userid or password invalid. Please help me in fixing it up.Here is the code:
    <%@page import="java.io.*,java.sql.*" %>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    </head>
    <body>
    <%
    String empid=request.getParameter("empid");
    String empname=request.getParameter("empname");
    String compid=request.getParameter("compid");
    String workplace=request.getParameter("workplace");
    String position=request.getParameter("position");
    String status=request.getParameter("status");
    String startingdate=request.getParameter("startingdate");
    ResultSet rs=null;
    Connection con = null;
    PreparedStatement ps = null;
    Statement st=null;
    try
    Class.forName("org.apache.derby.jdbc.ClientDriver");
    con = DriverManager.getConnection("jdbc:derby://localhost:1527/employee");
    out.println("got the connection");
    ps = con.prepareStatement("insert into employee values(?,?,?,?,?,?,?)");
    ps.setString(1,empid);
    ps.setString(2,empname);
    ps.setString(3,compid);
    ps.setString(4, workplace);
    ps.setString(5, position);
    ps.setString(6, status);
    ps.setString(7, startingdate);
    int n = ps.executeUpdate();
    if(n!=0){
    %>
    <br>
    <table style="background-color: #E3E4FA;"
    WIDTH="30%" border="1">
    <tr><th>Data is inserted successfully
    in database.</th></tr>
    </table>
    <%}
    st=con.createStatement();
    rs=st.executeQuery("select * from EMPLOYEE");
    while(rs.next())
    out.println("emp id:"+rs.getString(1)+" "+"empname:"+rs.getString(2)+" "+"compid:"+rs.getString(3)+" "+"workplace:"+rs.getString(4)+" "+"position:"+rs.getString(5)+" "+"status:"+rs.getString(6)+" "+"startingdate:"+rs.getString(7));
    catch (Exception e) {
    out.println("unable to connect to database" +e.getMessage());
    } finally {
    try {
    if(rs!=null)
    rs.close();
    out.println("resultset closed");
    if (con!= null) {
    con.close();
    out.println("connection closed");
    } catch (Exception e) {
    out.println("error occured" +e.getMessage())
    %>
    </body>
    </html>

    I've tried it by giving username and password it displayed the message "got the connection" followed by unable to connect to databaseSchema 'NBUSER' does not exist connection closed.This message is displayed from catch block is this problem because of using java DB.

  • Select * and Insert question

    I have my ResultSet and Query to get the data form an Oracle database. Would I use the same rs for an executeUpdate statement? Or how would I go about doing that?
    Basically I'm querying the database, getting the resultset, processing the data around, and then inputing the processed data as a new row in the same database. I have the first part down pat, but I'm a little hazy on the 2nd part, the INSERT INTO bit.
    Any help would be greatly appreciated.

    This is my code:
    public class LimitCheck extends HttpServlet
         private static int UsageAmount = 0;
         private static double TotalPurchased = 0.00;
         private static String Maybe = "Blurbo!";
         private static String Third = "Snafu!";
         private static int CustID = 0;
         private static void loadOracleJDBCDriver () {
    System.out.println ("Loading database driver...");
    try {
         DriverManager.registerDriver ( new oracle.jdbc.driver.OracleDriver());
    System.out.println ("Database driver loaded...");
    catch (SQLException e) {
    System.err.println (e.getMessage ());
    System.exit (1); // Driver error
    private static Connection getConnected () {
    System.out.println ("LC getting connection...");
    try {
    String jdbc_url = "jdbc:oracle:thin:@localhost:1521:oracle";
    Connection conn = DriverManager.getConnection (jdbc_url, "scott", "tiger");
    System.out.println ("LC connection created ...");
    return conn;
    catch (SQLException e) {
    System.err.println (e.getMessage () ) ;
    System.exit (1); // Driver failure
    return null;     // never happen
         private static Statement makeStatement (Connection conn) {
    try {
    System.out.println ("LC Making a Statement...");
    Statement stmt = conn.createStatement ();
    System.out.println ("LC Statement created...");
    return stmt;
    catch (SQLException e) {
    System.err.println (e.getMessage () ) ;
    System.exit (2); // Driver failure
    return null;     // never happen
    private static ResultSet openResultSet (Statement stmt, String query, String update) {
    try {
    System.out.println ("LC Creating resultSet...");
    ResultSet rs = stmt.executeQuery (query);
                   stmt.executeUpdate(update);
    System.out.println ("LC Resultset created...");
    return rs;
    catch (SQLException e) {
    System.err.println (e.getMessage () ) ;
    System.exit (3); // ResultSet error
    return null;     // never happen
         private static void processResultSet (ServletOutputStream out, ResultSet rs)
    try {
    System.out.println ("\n\n+++++ Processing ResultSet for LimitCheck+++++\n");
                   while (rs.next() )
                        CustID = (rs.getInt(2));
                        System.out.println(rs.getInt(2));
                        UsageAmount = UsageAmount + 1;
                        System.out.println(rs.getString(5));
                        System.out.println(rs.getDouble(4));
                        TotalPurchased = TotalPurchased + rs.getDouble(4);
    System.out.println ("\n\n+++++ ResultSet Processed for LimitCheck+++++\n");
              catch (SQLException e) {
    System.err.println (e.getMessage () ) ;
    System.exit (5); // Processing error
    private static void closeThingsDown (ResultSet rs, Statement stmt, Connection conn) {
    try {
    System.out.println ("LC Closing Things Down...");
    rs.close();
    System.out.println ("LC ResultSet Closed...");
    stmt.close ();
    System.out.println ("LC Statement closed...");
    conn.close();
    System.out.println ("LC Connection closed...");
    catch (SQLException e) {
    System.err.println (e.getMessage () ) ;
    System.exit (5); // Closure failure
    Then I have my doGet, and in it I have:
    ResultSet rs = openResultSet (stmt, query, update);
    processResultSet (out, rs);               
    closeThingsDown (rs, stmt, conn);
    When I javac it, I don't get any errors, but when I try to run it, my server craps out and the page can't be displayed. The problem is in my openResultset somewhere, but I can't see where.
    I have a sneaking suspicion that the update is supposed to come after I processResultSet, but it complains if I move the update to after it.

  • Reversing TECO status for Multiple WBS elements

    Hi,
    Question on setting and then reversing TECO status for a WBS element.
    When a project is closed technically in project builder, all underlaying items (wbs, network/activity) are technically closed as well.
    When you try to undo this, only the status of the top element is changed, not the underlaying items.
    Is there any way in which we get the underlaying items changed as well (mass change is not an option)
    Regards,
    Jatinder Bansal

    You can try two methods :-
    1.  Open project in project builder, Select project definition and then go to WBS Overview under project definition, now select all WBS Element and then undo TECO status. Now all the WBS status will be updated. But, this will not have any effect on network and its activities.
    2. Open the project in planning board, now select all the objects, now undo the TECO status. This will change the status of all selected objects like WBS,Network and activites....

  • Inspection Lot Status UD ICCO SPCO ORRQ

    Hello Experts,
    Please share your thoughts on the System Status "UD ICCO SPCO ORRQ". Not sure on why the Lot getting the status ORRQ "Order record required"
    What is the Condition in which the system triggers this Status? how to complete the inspection processing once we get this status? Is it a Particular Configuration setting that expects a Process Order Record?
    Is there any setting in Production that sets the Inspection Lot status as ORRQ.
    Appreciate your quick response.
    Regards
    Raja

    hi,
    Check ur MM- QM view whether QM order is assigned or not. if QM order is assigned then process your order and confirm it and provide the settlement also against that order. Or check any other order is opened against that lot or not Like PP order or PM order which is controlled by ur QM- status profiles.
    once ur order closed technically ur inspection process completed.
    Regards

Maybe you are looking for

  • Visual fortran calling a c function in visual studio

    Hi, I am running Windows 8.1 with Visual Studio Prof. 2012. I have installed Visual Fortran also. Now I wanted to make a solution with two projects one for Visual Fortran and one for C, and be able to call a C function from within the Fortran.  Can s

  • Itunes error on start up

    When i open itunes, you just see the outline and then it says an error occured and closes. Have tried uninstalling and reinstalling about 20 times. Whats gooooing ooooooonnnnnnnnnn?

  • Withholding tax lines are being cleared along with other line items

    Hi All, While doing J1INCHLN(payment making of TDS), system giving error i.e. "Withholding tax lines are being aleared along with other line items" Please suggest me in this issue...it would be great help for me. Thanks, Saisri

  • Unknown behaviour of interface TableModelListener

    Hi, I don�t succeed to implement interface TableModelListener in an inherited class of JTable. import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.Vector; import javax.swi

  • "Property currentLabel not found on String"

    This is the error message I keep getting with the following setup: I have several button instances onstage named "1gun", "2gun", "3gun" and so on. There are also several button instances onstage named "1bullseye","2bullseye" and so on. When I use thi