ResultSet.next() and resultset.islast() problem

I have query which returns 10 records. I run the using preparedStatement. When i use the while(resultSet.next()), the loop runs untill 10 records and after that when it come to the while check it hangs.
Sample code
pstmt= conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
while (rsAccessNoEq.next()) {...
Then i added the code in the while loop
if(rs.isLast()){
return;
For the first iteration itself the theisLast() is true and it terminates from the loop.
Please help me

public class ISP {
     private GFA gestorFic = null;
     private GCA gestorCad = null;
     private GBDAgestor = null;
     private String path = null;
     ServiceProcessVO javaIntra = null;
     ServiceProcessVO javaIntra1 = null;
     ServiceProcessVO javaIntra2 = null;
     ServiceProcessVO javaIntra3 = null;
     ArrayList dataList = null;
     List dataFile = null;
     ArrayList dataList1 = null;
     ArrayList dataList2 = null;
     ArrayList dataList3 = null;          
     public final void iP() throws SQLException,
     MCEA {
     ResultSet rsIntraHq = null;
          Connection connIntraHq = null;
          PreparedStatement pstmtIntraHq = null;
          ResultSet rsIntraFlow = null;
          Connection connIntraFlow = null;
          PreparedStatement pstmtIntraFlow = null;
          ResultSet rsEqNoAccess = null;
          Connection connEqNoAccess = null;
          PreparedStatement pstmtEqNoAccess = null;
          ResultSet rsAccessNoEq = null;
          Connection connAccessNoEq = null;
          PreparedStatement pstmtAccessNoEq = null;
          ResultSet rsFlowHqAccess = null;
          Connection connFlowHqAccess = null;
          PreparedStatement pstmtFlowHqAccess = null;
          dataList = new ArrayList();          
          dataFile = new ArrayList();
          System.out.println("At the begining :"+now() );
          dataFile = gestorFic.leerArchivo(path, file);
          System.out.println("After first step :"+now() );
          int size1 = dataFile.size();
          try {
               connAccessNoEq = gestor.getConnection();
               javaIntra = new ServiceProcessVO();
               pstmtAccessNoEq = connAccessNoEq
               .prepareStatement(ConsultasAssets.INTRA_ACCESS_NOEQ);
                         //ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
               pstmtAccessNoEq.setString(1, oti);
               pstmtAccessNoEq.setString(2, oti);
               pstmtAccessNoEq.setString(3, oti);
               rsAccessNoEq = pstmtAccessNoEq.executeQuery();
               //int k = rsAccessNoEq.TYPE_SCROLL_SENSITIVE;
               int i = 0;
               //rsAccessNoEq.last();
               while (rsAccessNoEq.next()) {
                    i++; System.out.println("Begin of loop:"+i);
                    javaIntra = populatedata(rsAccessNoEq, true);
                    dataList.add(javaIntra);
                    // Flow Hq Access
                    try {
                         connFlowHqAccess = gestor.getConnection();
                         javaIntra1 = new ServiceProcessVO();
                         pstmtFlowHqAccess = connFlowHqAccess
                         .prepareStatement(ConsultasAssets.HQ_ACCESS);
                         pstmtFlowHqAccess.setString(1, javaIntra
                                   .getCTASOCIACION().trim());
                         pstmtFlowHqAccess.setString(2, rsAccessNoEq.getString(1)
                                   .trim());
                         pstmtFlowHqAccess.setString(3, rsAccessNoEq.getString(3)
                                   .trim());
                         pstmtFlowHqAccess.setString(4,oti);
                         pstmtFlowHqAccess.setString(5,oti);
                         pstmtFlowHqAccess.setString(6,oti);
                         rsFlowHqAccess = pstmtFlowHqAccess.executeQuery();
                         while (rsFlowHqAccess.next()) {
                              javaIntra1 = populatedata(rsFlowHqAccess, false);
                              dataList.add(javaIntra1);
//                         if(rsAccessNoEq.isAfterLast()){
//                              return;
                    } catch (SQLException se) {
                         MCLA.logFatel(ClassNameAssets
                                   .getQualifiedClassName()
                                   + ": "
                                   + ClassNameAssets.getLineNumber()
                                   + ": "
                                   + "Error Occurred in HQ_ACCESS: "
                                   + se.getMessage());
                         throw new MigracionCommonExceptionAssets(se.getMessage());
                    } finally {
                         pstmtFlowHqAccess.close();
                         if (rsFlowHqAccess != null) {
                              rsFlowHqAccess.close();
                         //gestor.releaseConn(connFlowHqAccess);
     private SPVOpopulatedata(ResultSet rsCpProcess, boolean modify)
     throws SQLException {
          SPVOjavaIntra = new ServiceProcessVO();
          if (rsCpProcess.getString(ConstantesAssets.NU) != null
                    && !rsCpProcess.getString(ConstantesAssets.NU)
                    .equalsIgnoreCase(ConstantesAssets.BLANK))
               javaIntra.setNU(rsCpProcess.getString(
                         ConstantesAssets.NU).trim());
          if (rsCpProcess.getString(ConstantesAssets.NU_ASO) != null
                    && !rsCpProcess.getString(ConstantesAssets.NU_ASO)
                    .equalsIgnoreCase(ConstantesAssets.BLANK))
               javaIntra.setNU_ASO(rsCpProcess.getString(
                         ConstantesAssets.NU_ASO).trim());
          // HashTable logic to increament value for CTASOCIACION Start
          if (modify == true) {
               if (rsCpProcess.getString(ConstantesAssets.CTASOC) != null
                         && !rsCpProcess.getString(ConstantesAssets.CTASOC)
                         .equalsIgnoreCase(ConstantesAssets.BLANK)) {
                    char cha = ConstantesAssets.A;
                    if (tempMap.get(javaIntra.getNU()) != null) {
                         cha = tempMap.get(javaIntra.getNU()).toString()
                         .charAt(0);
                         cha++;
                    tempMap.put(javaIntra.getNU(), Character
                              .toString(cha));
                    javaIntra.setCTASOCIACION(((rsCpProcess
                              .getString(ConstantesAssets.CTASOC).trim()) + cha)
                              .trim());
          } else {
               javaIntra.setCTASOCIACION(rsCpProcess.getString(
                         ConstantesAssets.CTASOC).trim());
          // HashTable logic to increament value for CTASOCIACION End
          if (rsCpProcess.getString(ConstantesAssets.CCC) != null
                    && !rsCpProcess.getString(ConstantesAssets.CCC)
                    .equalsIgnoreCase(ConstantesAssets.BLANK))
               javaIntra.setCCC(rsCpProcess.getString(
                         ConstantesAssets.CCC).trim());
          if (rsCpProcess.getString(ConstantesAssets.FIV1) != null
                    && !rsCpProcess.getString(ConstantesAssets.FIV1)
                    .equalsIgnoreCase(ConstantesAssets.BLANK))
               javaIntra.setFIV(rsCpProcess.getString(
                         ConstantesAssets.FIV1).trim());
          if (rsCpProcess.getString(ConstantesAssets.FFV) != null
                    && !rsCpProcess.getString(ConstantesAssets.FFV)
                    .equalsIgnoreCase(ConstantesAssets.BLANK))
               javaIntra.setFFV(rsCpProcess.getString(
                         ConstantesAssets.FFV).trim());
          if (rsCpProcess.getString(ConstantesAssets.ES) != null
                    && !rsCpProcess.getString(ConstantesAssets.ES)
                    .equalsIgnoreCase(ConstantesAssets.BLANK))
               javaIntra.setES(rsCpProcess.getString(
                         ConstantesAssets.ES).trim());
          javaIntra.setI(ConstantesAssets.N);
          javaIntra.setN(ConstantesAssets.BLANK);
          javaIntra.setC(ConstantesAssets.BLANK);
          javaIntra.setCO(ConstantesAssets.BLANK);
          javaIntra.setFI(ConstantesAssets.BLANK);
          return javaIntra;
Please see the code
Siva

Similar Messages

  • ResultSet next and previous

    I have to Loop through a ResultSet.I have to use previous method inside the loop in certain condition.
    Is previous and next method efficient to use.I want to know wether the ResultSet uses indexes or each time it gets the data from the Database.
    I want to see the implementation of the ResultSet for my driver...how to see that.

    The real implementation is difficult to guess without looking into the code, and it may vary depending on the query/result set/optimizer settings.
    The result set is more a linked list (or Iterator) rather than a vector of rows. The previous() operation should be efficient in most cases, however, the previous row should be considered forgotten by default. the typical implementation is such that a number of rows is fetched from the database and cached in the local result set. Upon the first access to a row beyond the current rows cached, the cache is discarded and refilled.
    Whenever possible, use forward-only result sets, store PK fields locally, and issue separate update or delete statements. This should yield the best results in terms of performance.

  • Select Max and ResultSet Problem With Access

    The following code is producing a 'null pointer excepetion' error and I know why it is occurring I just do not know how to fix the problem.
    Basically I want to automitically generate a unique ID that is one number higher than the max ID (data is stored within an Access database). The ID field is made up of first and last initial taken from parsing previous login info ('JS-01', 'JS-02', ect.). If there are no IDs in the database that match your login info I want to set the new ID equal to 'JS-01' if your login is 'James Smith' for example.
    The problem is explained within the code below.
    <%
    //define resultset and statement
    ResultSet rss=null;
    ResultSet rs=null;
    Statement stmt=null;
    //HERE IS WHERE YOU PARSE THE LOGIN INFO
    String finitial = (String)session.getAttribute("vfirst");//vfirst=JIM
    String linitial = (String)session.getAttribute("vlast");//vlast=SMITH
    char f = finitial.charAt(0);
    char n = linitial.charAt(0);
    String sID = f+""+n;//NOW sID CONTAINS 'JS'
    try {
    //Using the current database connection create a statement
    stmt=con.createStatement();
    //QUERY TO SELECT MAX ID
    //NOTE: CURRENTLY THERE ARE NO IDs LIKE 'JS' IN THE DATABASE !!!!!!
    String sql="SELECT Max(ID) As MaxID FROM tblError Where ID LIKE '%"+sID+"%'" ;
    rs = stmt.executeQuery(sql);
    String newID;
    //HERE THE RESULT SET SHOULD BE NULL BUT IT IS NOT. I KNOW THIS BECAUSE WHEN I REPLACE String iID WITH A LITERAL LIKE 'JS-03' THE LOGIC WILL EXECUTE CORRECTLY AND GIVE ME 'JS-04'. IF I LEAVE THE CODE LIKE IT IS THEN I GET THE NULL POINTER VALUE ERROR BECAUSE YOU CANNOT RESOLVE "MaxID" WHEN THE RESULT SET IS NULL. IF THE RESULT SET IS NULL IT SHOULD NOT EVEN EXECUTE ANY OF THIS CODE WITHIN THE 'if' STATEMENT, BUT IT IS. SO BASICALLY JSP IS LEAVING ME WITH A MAJOR OXYMORON AND I WOULD APPRECIATE ANY ADVICE THAT WOULD HELP ME SOLVE THIS PROBLEM.
    if(rs.next()){
    String iID = rs.getString("MaxID");
    String letters = iID.substring(0,3);
    int numbers = Integer.parseInt(iID.substring(3,5));
    numbers = numbers + 1;
    if(numbers < 10){
    newID = letters + "0" + numbers;}
    else{
    newID = letters + numbers;
    else{//IF THERE IS NO RESULT SET THAN THE ID SHOULD BE 'JS-01'
    newID = sID + "-01";
    %>
    Because this an Access database I cannot use any null exception functions such as NVL or COALESCE which are specific to Oracle and SQL Server I beleive.

    The max() will return a result set, even if the max value is null.
    You should check to see if iID is null.
    if(rs.next())
       String iID = rs.getString("MaxID");
       if (iID == null)
           newID = sID + "-01";
       else
          String letters = iID.substring(0,3);
          ... etc ...
    }

  • WL 6.1 sp3 and ResultSet.next()

    Has anyone else had a problem with this call ?
    I'm running this on Win2000 and Oracle 8.1.6.
    ResultSet.next() seems to return true even after the cursor has passed the last row in the set. This was not an issue with WL6.1 sp1.

    I got the same problem. But finally I found that this is the problem with WL 6.1. This is resolved in sp3.
    So please verify the exact version of weblogic you are using.
    Note : Start weblogic from some sample domain before executing the following.
    java -classpath <wl_install_dir>/wlserver6.1/lib/weblogic.jar weblogic.Admin -url T3://<host>:<port> VERSION
    You should get similar to....
    WebLogic Server 6.1 SP3 06/19/2002 22:25:39 #190835
    WebLogic XML Module 6.1 SP3 06/19/2002 22:39:10 #190835

  • Problem with resultset.next inside 817 DB

    I have a java class running inside 817 database.
    I have a prepared statement that gets some records and loops through them and writes a record into another table.
    The SQL statement should produce 3000 records but only 566 get logged in the loop.
    I have looked at/tried everything. NOTHING seems wrong but jus tI dont get alll the records. The datatset is not truncated, records are missing ramdomly throught, ie recs 1-4 are OK then 5,6,7 are missing etc..
    Anyone know what the prb might be, its really weird and driving me nuts
    Rob
    null

    thank you for the pointers.
    For the RS is empty I've done a check with
    if(selectRs.next()!=null), even though
    next() is never suppose to be null, Yeah, you needn't bother with that. It's never supposed to be null, and if it is, there's a bug in the executeQuery method.
    ?so that confuses
    me. I've also put Sys.outs before & after the if
    statement & found it never prints out the System.out
    after the if(rs.next()). & I've stepped
    through with my WAS Debugger as a last restort to see
    what's going on. :$ So you're saying you put a print statement as the first statement right inside if (rs.next()) and it didn't get executed?
    I did do as you suggested with the
    count(*) & it did return a count of 1.You did that in your Java code? Changing only what you're selecting from those couple of columns to count(*), leaving the from and where alone?
    I am catching the SQLException for the try but
    nothing for the
    a_ruleSyntax.equals(current_ruleSyntax).Not sure what you're saying here, and not sure what your catch block looks like.
    I have put a System.out for if the equals returns
    false.
    Do you have any other ideas?Nope, sorry.
    If your answers to my questions above are "yes, that's what I'm doing," then I'm out of ideas, unless there's some exception that you're smothering.

  • TopLink and ResultSet: ojdbc14 vs. ojdbc6 - Closed command

    Hi all,
    I have problem with ojdbc library. We updated our ojdbc library from ojdbc14 to ojdbc6. But now, we have problem with SQLExcpetion: "java.sql.SQLException Closed statement".
    We have following code:
    Object result = session.executeQuery(query, args);
    Map map = (Map)((Vector)result).firstElement();
    // the data is in data type OracleResultSetImpl !!!
    OracleResultSet out_data = (OracleResultSet) map.get(EmtasConstant.GRID_PROCEDURE_DATA_OUT);
    OracleResultSetMetaData metadata = (OracleResultSetMetaData) out_data.getMetaData();
    If we used library "ojdbc14.jar" everything works fine, we get metadata, read data from resultSet, etc... No problem!
    But if we using "ojsbc6.jar" and call getMetadata, then throws: "java.sql.SQLException: Closed command: getMetaData" .. or "ava.sql.SQLException: Closed command: next()" or whatever we call on OracleResultSet out_data (we try OracleResultSet and ResultSet too)..
    If we used "ojdbc14.jar" and I call out_data.close(), they throws same exception => Why is the ResultSet in library ojdbc6.jar closed??????
    Any idea? I'm really stuck and I all day trying to come to solve the problem, but I resolved nothing.
    Pls help!
    Thx!
    Best regards, KLD!
    Sry for my English ;)

    Yes, I have newest version of TopLink (11.1.1. ...) and Java (1.6_09).
    Or, is any option how to convert ResultSet to any "normal" java object (like hasmap,collection, list, ...)
    I returned multiple cursor objects from stored procedure, and I resolved it as follows:
    More output cursors with StoredProcedureCall?
    but now I have problem with ResultSet and i don't want call more times the procedure call (first option)...

  • Control the loop of resultset.next( ); (method)

    Hai, guys
    I am using the ODBC database connection to (Excel Sheet) and i wanna get the records from it. My code is scucess but there is a problem in resultset.next() method.
    The thing is it retrieving all the data including the none data fields (null null), so finally it became a never ending loop.
    pls help me to get the data rang's records
    Statement stmnt = connexl.createStatement();
    String query = "SELECT * FROM [IJTS$]";
    stmnt.execute(query);
    ResultSet rsxl = stmnt.getResultSet();
    while(rsxl.next()) {
    String excelname = rsxl.getString(1);
    String excelcate = rsxl.getString(2);
    System.out.print(rsxl.getString(1));
    System.out.println(" "+rsxl.getString(2));
    }

    if null implies it has reached the last row, maybe you could check for null and break from the loop
    for example:
    while (rsxl.next()) {
      String excelname = rsxl.getString(1);
      String excelcate = rsxl.getString(2);
      if (excelname == null && excelcate == null) {
        break;
      } else {
        System.out.println(excelname + " " + excelcate);
    }

  • The ResultSet.next() returns false....

    Hai,
    I am working on jdbc. The connection credentials all correct, and its getting connected to the sybase without any problems. But I am not able to perform any 'select' or "update" statements...There are no exception or any errors...But the ResultSet.next() returns false and executeUpdate returns 0 . .
    I think you can help me.....Thanks...

    Yes the query is sameAs already pointed out, there are ONLY two possibilities.
    1. The query is not the same
    2. The database is not the same.
    You are making assumptions about what is going on and then drawing conclusions.
    You need to understand that you assumptions are wrong. So it doesn't matter what conclusion you draw.
    In terms of why the query isn't the same there could be any number of reasons but usually it is because you are passing in data and that data isn't what you think (assume) it is. It can also be that you are constructing the SQL and that construction is different. It could be that the environment that you use to test as settings which impact SQL.

  • Lockup in ojdbc14 Resultset.next()

    After several loops through the ResultSet handler, a subsequent call to ResultSet.next() results in a lockup.
    Below is a partial stack dump.
    Thread [Thread-14] (Suspended)
         oracle.jdbc.driver.SensitiveScrollableResultSet(oracle.jdbc.driver.ScrollableResultSet).prepare_refetch_statement(int) line: 2299 [local variables unavailable]
         oracle.jdbc.driver.SensitiveScrollableResultSet(oracle.jdbc.driver.ScrollableResultSet).refreshRowsInCache(int, int, int) line: 292
         oracle.jdbc.driver.SensitiveScrollableResultSet.refreshRow() line: 174
         oracle.jdbc.driver.SensitiveScrollableResultSet.handle_refetch() line: 255
         oracle.jdbc.driver.SensitiveScrollableResultSet.next() line: 82
         oracle.jdbc.driver.UpdatableResultSet.next() line: 251
         com.solcom.labelprintroom.DatabaseAccess.ordersForUserStatus(com.solcom.centraldb.CDBUser, java.lang.String) line: 291
    prepare_refetch_statement(int) is continuously looping between lines 2299, 2304, 2305.
    Connection is to an Oracle 8i (8.1.7) database.
    No exception is thrown and no timeout occurs. it merely loops continuously between the lines described in the Oracle driver.
    Is this a known problem? Is there a workaround?
    TIA
    AndyB

    "I have two DA classes with virtually the same code, just different queries."
    "In the other DA i do exactly the same..."Are these contradictory statements?
    Does anyone know if there is a problem with the Oracle
    Drivers or has anyone encountered a similair problem?Well, I am positive that -1 is not a problem for Oracle, it can use almost all the small negative numbers without error...
    Would it be possible to post a bit of your code to demonstrate how the code is different and how the SQL is different (or the same / not sure). There are infinite ways to code SQL with -1 in it, so what is important is exactly how you did it, which driver you are using, if you are using a Statement or PreparedStatement, if you are using connection pooling, etc.

  • Closing Statements and ResultSets

    I just recently realized that you need to close Statements and ResultSets in order to avoid getting the "Too many cursors"-message.
    My question is:
    Do you need to close both Statements and ResultSets?
    - not that it's a problem...
    if so:
    Does it matter which one you close first?

    I usually place the stmt.close() code in my finally block, to ensure that the statement gets closed, even if a SQLException occurs during the query/update. The ResultSet does not explicitly have to be closed, ... it is automatically closed when the Statement is closed, or if a new query is run on the same statement.

  • JDBC: Closing Connection does it close statement and resultset

    In my application I am facing ORA-0100 Maximum open cursors exceeded problem. We are executing quite a few queries and stored procedures before we close the connection object. But in few places statements and resultsets are not closed. Can these be a problem? Shouldn't they be automatically closed when the connection is closed?
    We are executing this block of code in a loop.

    in few places statements and
    resultsets are not closed. Can these be a problem?Yes.

  • ResultSet.next() throws exception

    I am working on a BEA Weblogic application migration from 7.1 to 8.1. My application has lots of Oracle user defined package functions for providing database query. Those functions return a cursor pointing to the query results (ResultSet object in JDBC). My BEA Weblogic 8.1 java application, which invokes those Oracle functions, uses getObject() method to get query ResultSet. Follows are a java code snippet and exception thrown when using ResultSet.next() method to move cursor. Thanks.
    =================== code snippet ========================
    CallableStatement cs1 = (CallableStatement)conn.prepareCall("{? = call pkg_profile.fn_get_user_data(?) }");
    cs1.registerOutParameter(1, java.sql.Types.OTHER);
    cs1.setString (2, c_strUsername);
    cs1.execute();
    // Get the Result
    ResultSet rs1 = (ResultSet)cs1.getObject(1);
    if (rs1 == null || !rs1.next()) { <=== exception thrown due to moving cursor to the next row of query result.
    =================== code snippet =======================
    Exception -
    ERROR 24 Nov 2004 12:19:28,527 USER:supuser - CNTXT:MISUserProfile.userDataDispatcher | SQL Error while retrieving data for user. | java.sql.SQLException: java.lang.NullPointerException: CDA is null
    Start server side stack trace:
    java.lang.NullPointerException: CDA is null
    at weblogic.db.oci.OciCursor.arrayFetch(Native Method)
    at weblogic.db.oci.OciCursor.oci_arrayFetch(OciCursor.java:2338)
    at weblogic.jdbc.oci.ResultSet.next(ResultSet.java:774)
    at weblogic.jdbc.rmi.internal.ResultSetImpl.next(ResultSetImpl.java:135)
    at weblogic.jdbc.rmi.internal.ResultSetImpl_WLSkel.invoke(Unknown Source)
    at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:362)
    at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:313)
    at weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java:821)
    at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:308)
    at weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:30)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:213)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:189)
    End server side stack trace

    Try this one...
    Before excecuting the query setAutoCommit false and then try to execute the query.After executing query manually do commit.It should work.

  • Resultset.next() Issue

    Okay I have narrow my issue down to activity involved with the resultset.next() method. What is happening is I am working through a small resultset--3 records. These records are made up of columns from 3 seaprate tables (9 total). Some of these tables have many records (> 3K) in them. I moved the SQL statement in a store procedure so we can execute the query in a faster manner. The store procedure is returning the information in only 46ms. However, when I start looking through the resultset on the app server, it is taking 19K ms for the first time through the loop.
    I am at a lost to explain why the first iteration is taking so long. I have looked back at the SQL statement. I use alias names for the tables. I identify the column names in the select statement, but I do not use aliases for the column names. I am wondering if my problem is connected to the fact that the Oracle Driver
    maybe going back to get the column names the first time through the result set. I am not using the column name to index into the resultset. If my theory is right, this would explain the high latency. If I am wrong, I am stumped.
    Any suggestions or help explaining this would be greatly appreciated.
    As always, thanks for reading my post.
    Russ

    Execution of a CallableStatement (Procedure) is relatively fast. Getting ResultSet back is fast. But First iteration over the result set takes a lot of time comparing to the following iterations.
    Part of the code :
    long start=System.currentTimeMillis();
    int i=0;
    long local=System.currentTimeMillis();
    while(rs.next()){
    if (i==0){
    MetricsUtil.printTime("ResultSetRowHolder.getRows(ResultSet rs) ["+list.size()+" ]",local);
    local=System.currentTimeMillis();
    hol=new ResultSetRowHolder(rs);
    list.add(hol);
    i++;
    if (i%100==0){
    MetricsUtil.printTime("ResultSetRowHolder.getRows(ResultSet rs) ["+list.size()+" ]",local);
    local=System.currentTimeMillis();
    MetricsUtil.printTime("ResultSetRowHolder.getRows(ResultSet rs) ["+list.size()+" ]",start);
    Printouts
    Metrics << QueryHelper.executeStatement() >> Total time -> 2.836 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [0 ] >> Total time -> 13.867 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [100 ] >> Total time -> 0.48 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [200 ] >> Total time -> 0.44 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [300 ] >> Total time -> 0.47 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [400 ] >> Total time -> 0.38 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [500 ] >> Total time -> 0.37 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [600 ] >> Total time -> 0.38 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [700 ] >> Total time -> 0.35 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [800 ] >> Total time -> 0.34 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [900 ] >> Total time -> 0.32 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [1000 ] >> Total time -> 0.34 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [1100 ] >> Total time -> 0.41 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [1200 ] >> Total time -> 0.32 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [1230 ] >> Total time -> 14.340 sec

  • ResultSet.next() throws NullPointerException

    Hello,
    When running the following code:
    import java.sql.*;
    class DatabaseDriver {
         private int                    databaseType;
         private String               error;
         private Connection     con;
         private Statement          statement;
         private ResultSet          rs;
         static final int          MYSQL_DB_TYPE = 1;
         static final int          PGSQL_DB_TYPE = 2;
         static final int          MSSQL_DB_TYPE = 3;
         static final int          ORACLE_DB_TYPE = 4;
         public DatabaseDriver (int dbType) {
              databaseType = dbType;
              try {
                   switch (dbType) {
                        case MYSQL_DB_TYPE:
                             Class.forName("com.mysql.jdbc.Driver").newInstance();
                             break;
                        case PGSQL_DB_TYPE:
                             Class.forName("org.postgresql.Driver").newInstance();
                             break;
                        case MSSQL_DB_TYPE:
                             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
                             break;
                        case ORACLE_DB_TYPE:
                             Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
                             break;
              } catch (Exception e) {
                   error = "could not load driver";
         public boolean connect (String server, String user, String password) {
              try {
                   con = DriverManager.getConnection("jdbc:mysql://" + server + "?user=" + user + "&password=" + password);
              } catch (Exception e) {
                   error = "could not connect to the database";
                   return false;
              return true;
         public boolean execQuery (String query) {
              try {
                   statement = con.createStatement();
                   if (statement.execute(query)) {
                        rs = statement.getResultSet();
                   while (rs.next()) {
                        System.out.println(rs.getString("1") + "\t" + rs.getString("2"));
                   rs.close();
                   rs = null;
                   statement.close();
                   statement = null;
              } catch (Exception e) {
                   error = e.toString();
                   e.printStackTrace();
                   return false;
              return true;
         public String getError () {
              return error;
         public boolean disconnect () {
              return true;
    class Test {
         public static void main (String[] args) {
              DatabaseDriver db = new DatabaseDriver(1);
              db.connect(args[0],args[1],args[2]);
              db.execQuery("USE " + args[3] + ";");
              db.execQuery("SELECT * FROM te;");
              System.out.println(db.getError());
    }I receive this in the printout:
    java.lang.NullPointerException
         at DatabaseDriver.execQuery(DatabaseDriver.java:61)
         at Test.main(Test.java:7)
    bla1     bla2
    bla6     bla7
    java.lang.NullPointerException
    Line 61
    while (rs.next()) {
    I have read a lot of other posts that say that the connection object is null or the recordset is empty, but it seems that neither of those are the case considering I am able to printout the two rows properly.
    Can someone please explain to me what I am doing wrong and how to fix it?
    Thanks

    You can pepper your code with System.out.println() statements to determine what value goes into the execute() statement before it runs.
    In the following, I think the first statement will probably return false. What is this sql trying to accomplish that you think it sould return true? Even if it returned true, what value do you expect in the resultSet?
    db.execQuery("USE " + args[3] + ";");
    db.execQuery("SELECT * FROM te;");
    As a side note, I strongly suggest you use connection pooling and not driverManager. here is an example of getting and returning a connection properly (all within a function)
    public String[] myFunction(){
    Connection conn=null;
    PreparedStatement pstmt1= null;
    ResultSet resultSet=null;
    ArrayList list1; //array that can grow in size
    try{
    list1=new ArrayList();
    conn= dataSource.getConnection();
    pstmt1= conn.prepareStatement();
    resultSet= pstmt1.executeUpdate();
    while(resultSet.next()){
    arrayList.add(resultSet.getString("lastName");
    return ( String[] ) arrayList.toArray( new String[arrayList.size()] );
    } catch (SqlException e){
    e.printStackTrace();
    } finally {
    if(rsultSet!=null)
    resultSet.close();
    if(pstmt1!=null)
    pstmt1.close();
    if(conn!=null)
    conn.close();
    }

  • Error message ResultSet.next not called

    I am a student learning java and am currently working on an assignement where I need to write jdbc programs that connect to an oracle database. The error message that I am getting is:
    ResultSet.next was not called.
    I do not know why I am getting this message. I wrote a simpler program to try to find the error, but I still got it again. Here's the part of the program:
    ResultSet rset = stmt.executeQuery ("SELECT billing_id_seq.NEXTVAL Next_SeqNumber "+
                             "FROM Dual");
    int sequenceNumber=rset.getInt("Next_SeqNumber");
         while(rset.next()){
    System.out.println(sequenceNumber);
    Any ideas would be helpful. Thanks very much!

    I am not really sure if it is okay to post the whole program on this message board, but here it is:
    import java.sql.*;     //Import Java's JDBC classes
    public class CalculateEnrollFinalGrades {
    public static void main(String[] args) {
    //Invoke the processEnrollRecords() method
         processEnrollRecords();
    } //end main()
    // The following method issues a SQL SELECT statement to the database that returns the section_id
    // and student_id for ALL rows from the enrollment_copy table. For each row received back in the
    // result set, a call should be made to the updateEnrollFinalGrade() method. See below for
    // information about what the that method does and what arguments it takes.
    public static void processEnrollRecords() {
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver"); // Load the Oracle JDBC driver
    catch (java.lang.ClassNotFoundException e) {
    System.out.println(e.getMessage());
    try {
    //Create the connection and statement objects
         Connection conn= DriverManager.getConnection("jdbc:oracle:oci8:@", "STUDENT","LEARN");
         Statement stmt=conn.createStatement();
    //Execute a query in the CTA database which returns section_id and student_id for all
    //rows of the enrollment_copy table
         int sectId=0;
         int studId=0;
         String sqlQuery="SELECT section_id, student_id "+
                   "FROM enrollment_copy";
         ResultSet rset= stmt.executeQuery(sqlQuery);
    //For each record returned in the ResultSet object, pass
    //the current connection object along with each section_id and student_id as
    //arguments to a method called updateEnrollFinalGrade()
         //while(rset.next()){
         sectId=rset.getInt("section_id");
         studId=rset.getInt("student_id");
         updateEnrollFinalGrade(conn, sectId, studId);
         //}//close while
    //Close all resources before the program ends
         //conn.close();      //should this be kept open???
         stmt.close();
         rset.close();
         return;
    catch (java.sql.SQLException e) { 
    System.out.println(e.getMessage());
    } // end processEnrollRecords()
    // calculate a final_grade for the specified student
    // and section, and then it updates the enrollment_copy table with the final_grade.
    private static void updateEnrollFinalGrade(Connection conn_p, int sectionId_p, int studentId_p) {
    try {
         Connection conn= DriverManager.getConnection("jdbc:oracle:oci8:@", "STUDENT","LEARN");
         Statement stmt=conn.createStatement();
         //query returns one row which is the final grade for the course for a particular student id and section.
         String sqlQuery2= "SELECT "+
         "ROUND(SUM((SUM(g.numeric_grade))/(COUNT(g.grade_type_code))*(gtw.percent_of_final_grade/100))) finGrade "+
         "FROM grade g, grade_type_weight gtw "+
         "where g.section_id=gtw.section_id AND g.grade_type_code=gtw.grade_type_code "+
         "AND g.student_id=? "+
         "AND g.section_id=? "+
         "GROUP BY gtw.percent_of_final_grade";
         PreparedStatement pstmt=conn.prepareStatement(sqlQuery2);
         pstmt.setInt(1, studentId_p);
         pstmt.setInt(2, sectionId_p);     
         ResultSet rsetGrade=pstmt.executeQuery();
         int finalGrade=rsetGrade.getInt("finGrade");
    //Once the final_grade has been calculated, use a different PreparedStatement object to
    //store it in the related enrollment_copy record. You need to use a Prepared
    //Statement
         String sqlUpdate=      "Update enrollment_copy "+
                        "SET final_grade=? "+
                        "WHERE student_id=? AND section_id=?";
         PreparedStatement pstmtUpdate=conn.prepareStatement(sqlUpdate);
         pstmtUpdate.setInt(1,finalGrade);
         pstmtUpdate.setInt(2,studentId_p);
         pstmtUpdate.setInt(3,sectionId_p);
         pstmtUpdate.executeUpdate();
         pstmt.close();
         pstmtUpdate.close();          
         stmt.close();
         rsetGrade.close();
         return;
    } // end try block
    catch (java.sql.SQLException e) { 
    System.out.println(e.getMessage());
    } //end updateEnrollFinalGrade()
    } //end CalculateEnrollFinalGrades
    Thanks very mush for your help.

Maybe you are looking for

  • [Solved] Cannot "su" properly in a terminal due to a .bashrc error

    The problem is simple:  I cannot su to my root account properly.  I can do so successfully in that I can become "root" but I get no output on the screen after typing in a command.  E.g., this is what my terminal shows after su'ing to root and typing

  • Strange error: COMPUTE_BCD_OVERFLOW

    Hi everyone, i have a very very strange error/exception trying to divide 2 Numbers: The source code looks like this: lv_alt_koeff = ABS( lv_alt_wrbtr_delta / ( lv_alt_wrbtr_h - lv_alt_wrbtr_s ) ). Values are: lv_alt_wrbtr_delta = 119201.40 lv_alt_wrb

  • Query slow after upgrade

    Hi All, Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production We have upgraded to 11g, however, many queries in our DB is running slow. I have pasted the trace file one of the query which is part of the procedure. this query is

  • Finder crashes when Preview column is active in list view

    I've created a bootable system backup of OS X 10.10.1 on an external 1TB HD connected via firewire 800 to a 2011 iMac running OS 10.10.1. I have had no problems with Yosemite's Finder on the iMac if I boot from the internal HD. I check to be sure whi

  • Frequency measurement using Labview 8 and Fieldpoint FP-CTR-502 - wind speed measure

    All the information regarding this kind of application seems to be outdated, I did not find no solution or example to construct frequency measurement VIs using Labview 8 The examples at "NI Discussion Forums : Most Active Hardware Boards : FieldPoint