ResultSet next() w/ threads

Hi,
I have a problem to get a complete set of records when using the next() method. I'm running this w/ threads and using the Runnable method (run()) as a template method to run all select and other sql statements per a thread. There is an inner class in run() with a synchronized method, and I think, this synchronized method should be enough to protect sovereignty for each thread while they are doing their work. When several threads are invoked, it happens that once in a while I get all records, but if I repeat the same test then it seems as next() doesn't return all records always. I get an exception 'Exhausted ResultSet'. The problem seems to be irregular.
The question 2: How accurate and reliable is the method getTime()? How does it pick up the time? Is it using a clock in a system?
thank you

An Exhausted ResultSet usually comes from a Statement Object being
accessed simultaneously by more than one session. This can usually happen when your server is under heavy loading (though not the only reason) and the ResultSet object, being entirely dependent on the Statement Object that created it, is closed at the instant two session try to access the statement object simultaneously.
The result is the Statement Object trying to close the same ResultSet
Object twice.
So i guess ur resultset and statement are not snchronised.Do check out once

Similar Messages

  • JDBC ResultSet.next() Error

    Can anyone help me with this error? I am running this in AIX box (java 1.3) using OCI to VMS RDB Server. I get this error when looping through the ResultSet.next().
    Thanks
    --Elie
    Exception in thread "main" java.sql.SQLException: ORA-09100: Message 9100 not found; No message file for product=NATCONN, facility=GTW
    %SYSTEM-F-NOMSG, Message number 0000C1C4
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java(Compiled Code))
    at oracle.jdbc.oci8.OCIDBAccess.check_error(OCIDBAccess.java(Compiled Code))
    at oracle.jdbc.oci8.OCIDBAccess.fetch(OCIDBAccess.java(Compiled Code))
    at oracle.jdbc.driver.OracleResultSetImpl.next(OracleResultSetImpl.java(Compiled Code))
    at mbr.main(mbr.java(Compiled Code))

    I got it resolved by using NVL function on each of my DATE columns. I found a log from the RDB server complaining about dates. The NVL seems did the trick.
    Thanks again for your reply.
    --Elie                                                                                                                                                                                                                                                                                                                                                                                                           

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

  • 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

  • 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

  • ResultSet.next was not called

    I have this query ://Attempt The DB insert
    ResultSet rs = stmt.executeQuery("SELECT lhh_demo_id_seq.nextval from dual");
    String Demo_ID = rs.getString(1);
    while(rs.next()) {
    while (i < 2) {
    i++;
    rs.close();
    try
    Date date = dt.parse(birth);
    System.out.println("date " + date);
    stmt.executeUpdate( "insert into lhh_demo_reg values (" + Demo_ID + "," + RegNo + "," + Name + ",to_date('" + date+"','DD-Mon-YYYY')," + Center_ID + ")");
    catch(Exception e){}
    // Now Register a NULL Admission Record
    i = 0;
    rs = stmt.executeQuery("SELECT lhh_adm_id_seq.nextval from dual");
    String Adm_ID = rs.getString(1);
    while(rs.next()) {
    rs.close();
    stmt.executeUpdate("insert into lhh_adm_reg values (" + Adm_ID + "," + Center_ID +" , " + Demo_ID + ")");
    // Now Register a NULL Procedure Record
    i = 0;
    rs = stmt.executeQuery("SELECT lhh_proc_id_seq.nextval from dual");
    String Proc_ID = rs.getString(1);
    while(rs.next()) {
    while (i < 2) {
    i++;
    rs.close();
    stmt.executeUpdate("insert into lhh_proc_reg values (" + Proc_ID + "," + Center_ID + "," + Demo_ID + "," + Adm_ID +")");
    //Now Register a NULL Lesion Record
    i = 0;
    rs = stmt.executeQuery("SELECT lhh_les_id_seq.nextval from dual");
    String Les_ID = rs.getString(1);
    while(rs.next()) {
    while (i < 2) {
    i++;
    rs.close();
    but i keep getting ResultSet.next was not called...can anyone help please?

    I'm not sure what exactly you are trying to do ... but ...
    You seem to have several ResultSets in action. The first step is to find which of your "selects" is giving this exception. So, go ahead a enclose your statements within a try catch finally block. Use the finally block to close your result set (if not null).
    Once you narrow down the offending code, post back with the offending part of the code & the result you got with stack trace (if you still can't figure out what's happenning)
    HTH
    --Das                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

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

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

  • Resultset.next hangs waiting for socketread()

    Hi All,
    I am running an application which is trying to fetch a set of records using jdbc resultset but , sometimes, it hangs on the socketread and I am not sure what is the cause..Please help:
    Below is the piece of code and parameters are:
    start=1
    iBreakingLimit=30 when it hangs
    QueryTimeout=60 sec
    limit=60
    Hangs at:
    SocketInputStream.socketRead()
    OracleResultSet.close_or_fetch_from_next(boolean)
    ScrollableResultSet.next()
    dbStatement=dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                                          if(start>1)
                        rs.absolute(start-1);
                   int iBreakingLimit=0;
                   while (rs.next())
                        ++iBreakingLimit;
                        if(limit>0 && iBreakingLimit>limit)
                             break;
                                      }Edited by: Amer on Apr 15, 2009 7:49 AM
    Edited by: Amer on Apr 15, 2009 7:50 AM
    Edited by: Amer on Apr 15, 2009 7:50 AM
    Edited by: Amer on Apr 15, 2009 7:51 AM

    Hi Again,
    I wrote a sample class to test the connection and my select statement and I was able to reproduce it outside the application. This class has no update at all and it never returns (hangs at iteration number 7 for the first loop).... Another test (removing timeout set which I think it is not related) shows that it stops at Iteration 4 breaking limit 40 (so it is random).. Also, I tried with TRANSACTION_SERIALIZABLE and got same behavior . THIS does NOT happen with db2 driver using same sample.. Please help!!
    package com.udm.core.test;
    import java.sql.*;
    public class JDBCTest
         public static void main(String s[])
              JDBCTest t = new JDBCTest();
              try
                   for(int i=0;i<30;i++)
                        System.out.println("Call ="+i);
                        t.testme();
              catch(Exception e)
                   e.printStackTrace();
         public void testme() throws Exception
              String sUrl="jdbc:oracle:thin:";
              String sServer="xxxxxxxxxx";
              String sPort="xxxx";
              String sService="xxxxx";
              String sDriver = "oracle.jdbc.OracleDriver";
              String sUserName="xxxx";
              String sPassword="xxxxxx";
              String sSQL="select about 270 fields from table (pure select statement)";     
              Class<?> cDriverClass=Class.forName(sDriver);
              Driver dDriverObject=(java.sql.Driver)cDriverClass.newInstance();
              DriverManager.registerDriver (dDriverObject);
              String sServiceUrl=sUrl+"@"+sServer+":"+sPort+":"+sService;
              Connection dbConnection=DriverManager.getConnection (sServiceUrl,sUserName,sPassword);
              dbConnection.setAutoCommit(false);
              dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
              Statement dbStatement =dbConnection.createStatement();
              dbStatement.setQueryTimeout(60);
              ResultSet rs=dbStatement.executeQuery(sSQL);
              int iBreakingLimit=0;
              int limit=200;
              while (rs.next())
                   ++iBreakingLimit;
                   if(limit>0 && iBreakingLimit>limit)
                        break;
                   System.out.println("\tInside loop iBreakingLimit="+iBreakingLimit);
              rs.close();
              dbStatement.close();
    }Thread dump:
    Call =7
    Full thread dump Java HotSpot(TM) Client VM (1.5.0_16-b02 mixed mode):
    "OracleTimeoutPollingThread" daemon prio=10 tid=0x0ac89868 nid=0x1380 waiting on condition [0x0af0f000..0x0af0fbe8]
    at java.lang.Thread.sleep(Native Method)
    at oracle.jdbc.driver.OracleTimeoutPollingThread.run(OracleTimeoutPollingThread.java:158)
    "Low Memory Detector" daemon prio=6 tid=0x00a955e0 nid=0xeb4 runnable [0x00000000..0x00000000]
    "CompilerThread0" daemon prio=10 tid=0x00a942f8 nid=0xb30 waiting on condition [0x00000000..0x0abcfa48]
    "Signal Dispatcher" daemon prio=10 tid=0x00a93660 nid=0x172c waiting on condition [0x00000000..0x00000000]
    "Finalizer" daemon prio=8 tid=0x00a8a440 nid=0x12f0 in Object.wait() [0x0ab4f000..0x0ab4fa68]
    at java.lang.Object.wait(Native Method)
    - waiting on <0x02fd5d00> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:120)
    - locked <0x02fd5d00> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:136)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)
    "Reference Handler" daemon prio=10 tid=0x00a89008 nid=0xa58 in Object.wait() [0x0ab0f000..0x0ab0fae8]
    at java.lang.Object.wait(Native Method)
    - waiting on <0x02fd5d88> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:474)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116)
    - locked <0x02fd5d88> (a java.lang.ref.Reference$Lock)
    "main" prio=6 tid=0x00036af8 nid=0x1450 runnable [0x0007f000..0x0007fc3c]
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at oracle.net.ns.Packet.receive(Unknown Source)
    at oracle.net.ns.DataPacket.receive(Unknown Source)
    at oracle.net.ns.NetInputStream.getNextPacket(Unknown Source)
    at oracle.net.ns.NetInputStream.read(Unknown Source)
    at oracle.jdbc.driver.T4CMAREngine.getNBytes(T4CMAREngine.java:1520)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalNBytes(T4CMAREngine.java:1490)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalBuffer(T4CMAREngine.java:2004)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalCLR(T4CMAREngine.java:1791)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalCLR(T4CMAREngine.java:1925)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalDALC(T4CMAREngine.java:2347)
    at oracle.jdbc.driver.T4C8TTIuds.unmarshal(T4C8TTIuds.java:134)
    at oracle.jdbc.driver.T4CTTIdcb.receiveCommon(T4CTTIdcb.java:154)
    at oracle.jdbc.driver.T4CTTIdcb.receive(T4CTTIdcb.java:114)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:703)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:799)
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1039)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:839)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1124)
    at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:1272)
    - locked <0x02b2f5b0> (a oracle.jdbc.driver.T4CPreparedStatement)
    - locked <0x02b18e30> (a oracle.jdbc.driver.T4CConnection)
    at com.udm.core.test.JDBCTest.testme(JDBCTest.java:50)
    at com.udm.core.test.JDBCTest.main(JDBCTest.java:15)
    "VM Thread" prio=10 tid=0x00a86540 nid=0xfec runnable
    Edited by: Amer on Apr 17, 2009 6:45 AM
    Edited by: Amer on Apr 17, 2009 6:45 AM
    Edited by: Amer on Apr 17, 2009 6:47 AM
    Edited by: Amer on Apr 17, 2009 6:48 AM
    Edited by: Amer on Apr 17, 2009 6:58 AM
    Edited by: Amer on Apr 17, 2009 7:05 AM

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

  • Jdbc ResultSet.next() problem

    this function is part of a class the extends AbstractTableModel
    the line of code that is causing all the problems is right below lines that are indented all the way to the right and are in all caps
    public void setAResultSet(ResultSet results)
    try
    ResultSetMetaData metadata =
    results.getMetaData();
    int columns = metadata.getColumnCount();
    //now we know how many columns there are, so
    //initialize the String array
    columnNames = new String[columns];
    //get the column names
    for(int i = 0; i < columns; i++)
    //remember - columns start with the indice at 1
    columnNames[i] = metadata.getColumnLabel(i+1);
    //get all the rows
    dataRows = new Vector();
    //will store the whole row of data
    String[] oneRow;
    while(results.next());
    //re-allocate memory each time, b/c its a whole
    //new row of data
    oneRow = new String[columns];
    //get the data in the current row, from every
    //column
    for(int i = 0; i < columns; i++)
    {   System.err.println("Indice: " + i);
    PROBLEM ON LINE BELOW
    EXCEPTION STATES "INVALID CURSOR STATE"
    oneRow[i] = results.getString(i+1);
    //all of the data is collected, so store
    dataRows.addElement(oneRow);
    fireTableChanged(null);
    catch(SQLException sqle)
    System.err.println("Error in ResultsModel.setResultSet()");
    System.err.println(sqle.getMessage());
    Anyone has an idea as to why the SQLException is being thrown? Why is the cursor state invalid???

    Hmmmm, try setting the cursor to the first row in the
    result set just before you wish to get the data. That led to some interesting results. Here's what I added:
    while(results.next());
    //re-allocate memory each time, b/c its a whole
    //new row of data
    oneRow = new String[columns];
    boolean texe = results.first();
    THE REST IS THE SAME AS BEFORE
    This also threw a SQLException, with the message: "Result set type is TYPE_FORWARD_ONLY"
    That's very interesting b/c I know that its doing this from iteration 1. I know this because I have an err.println() message in the for loop that's nested in the while loop. That message, which tells me what i equals, did NOT show up. So, going to the first column somehow went backwards causing an error (but I've never had a problem using previous() or any other "backwards" methods for ResultSet objects before!). And where the cursor so going to first() is backwards? Whoever can figure this out deserves Duke Dollars.

Maybe you are looking for