Determining Number of Rows in a ResultSet

Hi,
Is there an easy way to determine the number of rows in a result set with TYPE_FORWARD_ONLY?

> > Try ResultSet rs = statment.executeQuery(...);
if(rs
== null){ //result set is empty}That is incorrect... it should have read:
ResultSet rs = statment.executeQuery(...);
if( ! rs.next() )
//result set is empty
you're right!! copy/paste from executeUpdate( ) api documentation about statements....
"a ResultSet object that contains the data produced by the given query; never null"
here's the catch though: that will advance your result set, which will throw off your cursor in a while loop (used to parse the results). requires you to reset the cursor before processing the result set.

Similar Messages

  • Trying to find the number of rows in a ResultSet

    I am trying to find the number of rows in a ResultSet, using the following code:
    rs = st.executeQuery(query);
    rs.last(); // to move the cursor to the last row
    System.out.println(rs.getRow());
    However, I am getting this error:
    java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Unsupported method: ResultSet.last
    Whats going wrong??

    praveen_potru wrote:
    You might have not used scrollable result set..
    Try like this:
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);rs = stmt.executeQuery(sqlString);
    // Point to the last row in resultset.
    rs.last();
    // Get the row position which is also the number of rows in the ResultSet.
    int rowcount = rs.getRow();
    System.out.println("Total rows for the query: "+rowcount);
    cheersAnd I hope the OP would read it because the thread is a year old.

  • How do you return the number of Rows in a ResultSet??

    How do you return the number of Rows in a ResultSet? It's easy enough to do in the SQL query using COUNT(*) but surely JDBC provides a method to return the number of rows.
    The ResultSetMetaData interface provides a method for counting the number of columns but nothing for the rows.
    Thanks

    No good way before JDBC2.0. u can use JDBC2.0 CachedRowSet.size() to retrieve the number of rows got by a ResultSet.

  • Number of rows in a ResultSet

    DB: Release 8.1.5.0.0
    Server: DEC Alpha OSF1 V4.0F
    Driver: thin, version?
    We're using JDBC to access Oracle tables from classes loaded into the database with loadjava. I can execute a statement and get a ResultSet, but I haven't been able to find a way to get the number of rows in the ResultSet (since Oracle's implementation of JDBC doesn't include the getFetchSize method of ResultSet).
    Is there another way to get the size of a ResultSet? If not, will Oracle be adding the getFetchSize method to their implementation soon?
    Thanks.
    null

    > > Try ResultSet rs = statment.executeQuery(...);
    if(rs
    == null){ //result set is empty}That is incorrect... it should have read:
    ResultSet rs = statment.executeQuery(...);
    if( ! rs.next() )
    //result set is empty
    you're right!! copy/paste from executeUpdate( ) api documentation about statements....
    "a ResultSet object that contains the data produced by the given query; never null"
    here's the catch though: that will advance your result set, which will throw off your cursor in a while loop (used to parse the results). requires you to reset the cursor before processing the result set.

  • How to get the number of rows in a ResultSet

    Hello,
    I'm an intern and I'm trying to get the number of rows from result set in oracle using rs.last() and rs.beforeFirst() methods
    but I got an error. Could Below is my sample code:
    import java.sql.*;
    public class SarueckConnect {
    public static void main(String[] args) {
    Connection con = null;
    Statement stmt = null;
    ResultSet re = null;
    String[] ParamArray;
    ParamArray = new String[24];
    //Properties logon;
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver"); //Loading the Oracle Driver.
    con = DriverManager.getConnection
    ("jdbc:oracle:thin:@258.8.159.215:1521:test_DB","data","data"); //making the connection DB.
    stmt = con.createStatement ();// Sending a query string to the database
    //stmt.executeUpdate("UPDATE test_table set steuk = 6 WHERE steuk = 5");
    ResultSet rs = stmt.executeQuery("SELECT mandt,kokrs,werks,arbpl,aufnr,vornr,ile01,"+
    "lsa01,ism01,ile02,lsa02,ism02,ile03,lsa03,ism03,ile04,lsa04,ism04,steuk,matnr,budat,"+
    "kostl,pernr,rueckid FROM test_table where steuk =6");
    //Print the result out.
    rs.last(); //This is the line which gives an error.
    int rows = rs.getRow();
    rs.beforeFirst();// I presume this is wrong to.
    ParamArray = new String[24*rows];
    int counter=0;
    while (rs.next()) {
    for (int i = 1; i <= 24; i++){
    ParamArray[i-1+(counter*24)] = rs.getString(i);
    System.out.print(rs.getString(i) + '\t');
    System.out.println();
    counter++;
    } catch(Exception e) {
    e.printStackTrace();
    } finally {
    try
    if(stmt != null) stmt.close();
    if(con != null) con.close();
    } catch (Exception exception) {
    exception.printStackTrace();
    TryBapi sap = new TryBapi(ParamArray);
    }When I run the code I do have the following ERROR Message:
    java.sql.SQLException: Invalid operation for forward only resultset : last
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
    at oracle.jdbc.driver.BaseResultSet.last(BaseResultSet.java:91)
    at SarueckConnect.main(SarueckConnect.java:28)Please could any body Help me out here to figure out how to correct this?
    Any Help would be highly apprecited.

    make your result set scrollable...Not such a good idea. With Oracle, the JDBC driver will read and cache all the ResultSet in memory (with other DBMSs/drivers the behavior will probably be different, but you will still have some unnecessary overhead).
    You can do the caching yourself if you think it's worth it. If the piece of code you posted is why you need this for, then use a List or Vector and you won't need to know the size upfront.
    Alin,
    The jTDS Project.

  • Getting the number of rows returned from ResultSet

    Hi,
    Does anyone know a method to get the number of rows returned with a query using the Resultset class?
    Thanks.

    Hi 281080,
    If your database and JDBC driver support it, in order to use the solution that da-alexj has suggested, you need to create a 'scrollable' "ResultSet" -- the javadoc for method "createStatement()" (in class "java.sql.Connection") has more details.
    However, I have found with Oracle 8.1.7.4 database and Oracle (thin) JDBC driver, that part of their implementation of the "last()" method (in class "java.sql.ResultSet") is to actually iterate through the entire "ResultSet" in order to reach the last row. If your "ResultSet" is very large (I tested it with a 100,000 row "ResultSet"), this will take a long time.
    Just wanted to make you aware of that.
    Of-course, this may be irrelevant to you since I didn't see any mention in your post of what database and JDBC driver you are using.
    Hope this has helped you, anyway.
    Good Luck,
    Avi.

  • How to know the number of rows of a ResultSet

    Hello.
    I'm trying to detect the number of rows of a query result before making all the results.next().
    Until know, my way was:
    ResultSet results = sql.executeQuery();
    while( results.next() )
    int i = 0;
    ... do stuff ...
    i++;
    out.println("The number of rows is: " + i);
    But I would like to know the value of 'i' just after 'executeQuery'.
    Does anybody have any experienc?
    Regards.

    How about like this???
    >
    ResultSet results = sql.executeQuery();results.last();
    i = results.getRow();
    results.first();
    while( results.next() )
    int i = 0;
    ... do stuff ...
    i++;
    out.println("The number of rows is: " + i);
    But I would like to know the value of 'i' just after
    'executeQuery'.
    Does anybody have any experienc?
    Regards.

  • Setting the maximum number of rows in a ResultSet

    Hi everybody,
    Anyone knows if it is possible to set the maximum number of rows to obtain in a ResultSet using JDBC 2.0, and if so, how to do it?
    Thanks in advance.

    Statement st = con.createStatement();
    st.setFetchSize(no_of_rows_here);
    ResultSet rs = st.executeQuery(query);Sudha

  • Determine number of rows from javascript so I can hide if zero

    Hi All,
    Found a great article which I adapted to use the link on a report to delete a row in db and remove from table (without a refresh).
    It works great except I want the region to not display when there are no rows left.
    Currently it shows "No Data Found" but because the page does not submit the region does not hide.
    Here is the Java code:
    function ackMsg(p_this, p_empno) {
    // get the table row on which the user clicked
    var tr = $(p_this).closest('tr');
    // perform an asynchronous HTTP AJAX request using jQuery
    $.ajax({
    type: "POST",
    url: "wwv_flow.show",
    data: {
    p_flow_id: $('#pFlowId').val(),
    p_flow_step_id: $('#pFlowStepId').val(),
    p_instance: $('#pInstance').val(),
    x01: p_empno, // assign p_empno to the g_x01 global variable
    p_request: "APPLICATION_PROCESS=ack_message" // refer to the application process
    beforeSend: // executes while the AJAX call is being processed
    function() {
    // delete following HTML classes from the table row element
    // could be possibly theme dependent
    tr.removeClass('even');
    tr.removeClass('odd');
    // use jQuery's animate function to give the table row, and its children, a red background
    tr.children().hover(function() {
    tr.children().animate({'backgroundColor': '#00cc00'}, 300);
    }, function() {
    tr.children().animate({'backgroundColor': '#00cc00'}, 300);
    tr.children().animate({'backgroundColor': '#00cc00'}, 300);
    success: // to be called if the request succeeds
    function() {
    jQuery(p_this).trigger('apexrefresh');
    // jQuery has difficulties animating inline elements
    // that's why we wrap them in a div, which is a block element
    tr.children().wrapInner('<div>').children().fadeOut(400, function() {
    tr.remove(); // visually remove the row from the report
    I did some Googling to add the line ' jQuery(p_this).trigger('apexrefresh');' which refreshes just that report.
    What I think I need to do is add a check for number of rows left after the refresh then if = 0 do full page refresh to allow the region condition to hide it.
    Unfortunately after hours on Google I can't find how to check how many rows are in the table.
    PS the function is called from the link in the report like this onclick="ackMsg(this, #ACK#)"
    Please help
    AT
    Edited by: user1678248 on May 13, 2013 9:39 PM
    Edited by: user1678248 on May 13, 2013 9:40 PM

    1)
    When you set a column to hidden in a classic report using the method I described, it creates hidden form elements for that column.
    <tt><input type="hidden" name="f01" value="" id="f01_0002"></tt>
    You should inspect the source to figure out the name value.
    Since this belongs to the wwv_flow form, we can therefore get this data with: wwv_flow.f01
    Alternatively, you could have used the apex_item API to achieve the same result, which probably gives a bit better control.
    http://docs.oracle.com/cd/E37097_01/doc/doc.42/e35127/apex_item.htm#CHDBFHGA
    select apex_item.hidden(1, col) || col col
    from table
    Set that column to a standard report column so it doesn't escape the html.
    You can also reference the data in these fields using PL/SQL using the apex_application API:
    http://docs.oracle.com/cd/E37097_01/doc/doc.42/e35127/apex_app.htm#CHDGJBAB
    2)
    As above, setting the column to hidden creates hidden elements on the page. It is simply f01 because that is the only hidden field I would have on my page. With four reports on the page, you would need to be careful not to do the same on the other reports, as you would get inaccurate data. For each report, setting columns to hidden always starts with f01. In that, you would be best to use the apex_item API.
    I actually initially ran into this issue when i had a tabular form on the same page as a report with hidden fields, which was causing conflicts in the page processes.
    Hope it helps.

  • Getting number  of rows in a resultset

    I am moving my application from JDBC 1.0 to JDBC 2.0. In JDBC 1.0, I used to fire separate query for count(*) to get the no. of rows in results but with JDBC 2.0 is there way that I dont need to execute a separte query to get no. or rows in a resultset.
    Thanks
    Sushil

    There is Sushil if your driver supports it. It can be done with scrollable ResultSets.
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = stmt.executeQuery("sql");
    if (rs != null) {
    rs.last();
    int numRows = rs.getRow();
    // be sure to set rs.beforeFirst() if you want to process the ResultSet
    }

  • Determine Number of  rows in Internal Table

    Hi,
      I have defined my internal table as follows:
         TYPES : BEGIN OF ABC_KEY,
                  FIELD1(2)   TYPE C,
                  FIELD2(1)   TYPE C,
                  FIELD3(8)   TYPE N,
                  END OF ABC_KEY.
    DATA: itab1 TYPE TABLE OF ABC_KEY
                      WITH KEY FIELD1,
           wa_lines_1 LIKE LINE OF itab1.
    How can I retrieve the number of rows in Internal Table?
    Thanks.
    Regards,
    bw_newbie

    You can define the number of rows of the internal table using the DESCRIBE itab command .
    As the rest have already stated a sample code snippet .
    For more info type in DESCRIBE in your prgram and click on (F1) by placing the cursor on DESCRIBE .
    You will find more options as to how you can use the DESCRIBE command according to your requirement .
    Thanks ,
    Hari

  • Determining number of rows in blocks

    Hello
    Assume 8k blocksize
    How can I know, how many rows will fit into one block?
    Cheers

    Not really no. What's a row look like? NUMBERs? VARACHARs? DATE types? If VARCHARs, the amount of data actually being stored could vary hugely.
    If you already have some data loaded in a table somewhere, you may try sampling existing data to give you some idea.
    Try something like this:
    MBOBAK@mstmfgpep> create table test_rows nologging as select * from dba_tables;
    Table created.
    MBOBAK@mstmfgpep> select count(*) from TEST_ROWS;
      COUNT(*)
          1589
    1 row selected.
    MBOBAK@mstmfgpep> l
      1* select dbms_rowid.ROWID_to_absolute_fno(rowid,'MBOBAK','TEST_ROWS'),dbms_rowid.ROWID_BLOCK_NUMBER(rowid),count(*) rows_in_block from test_rows group by dbms_rowid.ROWID_to_absolute_fno(rowid,'MBOBAK','TEST_ROWS'),dbms_rowid.ROWID_BLOCK_NUMBER(rowid)
    MBOBAK@mstmfgpep> /
    DBMS_ROWID.ROWID_TO_ABSOLUTE_FNO(ROWID,'MBOBAK','TEST_ROWS') DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID) ROWS_IN_BLOCK
                                                               6                                  212            31
                                                               6                                  216            32
                                                               6                                  218            31
                                                               6                                  221            31
                                                               6                                  222            32
                                                               6                                  224            31
                                                               6                                  255            31
                                                               6                                  206            32
                                                               6                                  213            32
                                                               6                                  220            31
                                                               6                                  223            31
                                                               6                                  225            32
                                                               6                                  227            31
                                                               6                                  239            30
                                                               6                                  245            31
                                                               6                                  208            32
                                                               6                                  211            32
                                                               6                                  240            30
                                                               6                                  243            31
                                                               6                                  247            33
                                                               6                                  253            34
    DBMS_ROWID.ROWID_TO_ABSOLUTE_FNO(ROWID,'MBOBAK','TEST_ROWS') DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID) ROWS_IN_BLOCK
                                                               6                                  204            32
                                                               6                                  228            31
                                                               6                                  230            31
                                                               6                                  232            31
                                                               6                                  234            31
                                                               6                                  235            30
                                                               6                                  250            41
                                                               6                                  254            33
                                                               6                                  256            31
                                                               6                                  207            31
                                                               6                                  237            30
                                                               6                                  241            31
                                                               6                                  242            32
                                                               6                                  244            32
                                                               6                                  246            31
                                                               6                                  248            38
                                                               6                                  251            34
                                                               6                                  209            32
                                                               6                                  231            31
                                                               6                                  236            30
                                                               6                                  238            30
    DBMS_ROWID.ROWID_TO_ABSOLUTE_FNO(ROWID,'MBOBAK','TEST_ROWS') DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID) ROWS_IN_BLOCK
                                                               6                                  210            32
                                                               6                                  214            32
                                                               6                                  215            32
                                                               6                                  219            31
                                                               6                                  226            31
                                                               6                                  205            32
                                                               6                                  229            31
                                                               6                                  252            34
    50 rows selected.
    MBOBAK@mstmfgpep> This will count the number of rows that you're actually getting in each block. Warning, on a large table, this could take a very long time to run and produce lots of output. But you should be able to use the technique to sample how many rows/block you see on various tables.
    Hope that helps,
    -Mark

  • How do I find out the number of rows in a resultset ?

    Without scrolling it.

    And explain to me, oh sarcastic one, how it wouldn't be a better idea to put that data into a datastructure and pass that back.1. Performance with very large ResultSet objects for which only sparse data is desired (that's what pages are for).
    2. Resource optimization.
    3. Efficient sequential processing.
    4. The ability to intelligently determine based on resource usage whether to page the results or use your implementation for small ResultSet objects.
    Answering your points:
    1. I just showed him a very easy way to get the size.
    2. I don't see any advantage of a collection (if that's what you were envisioning) over a paged ResultSet. Actually the ResultSet is a collection of sorts.
    3. Your data is reliant on the connection initially anyway. The collection would only provide an advantage in the possibly short window while the data was being viewed.
    4. You can always resort a ResultSet by requerying.

  • How do I get the number of rows in a ResultSet?

    I checked the API, but didn't find a method that does this.

    You could try calling last() then getRow() to get the
    no of rows ...You probably need a scrollable resultset to do this, so that you can
    rewind back to the start and read the data in.
    I imagine you want to get a count, to size an array, before reading in the data ? Why not load it in an arraylist, then convert to an array afterwards ?
    regards,
    Owen

  • Same old...number of rows in a resultset...but a different question

    Hi,
    I'm writing a code to generate report from the database. Everything is working absolutely fine. Now the problem is that when I try to check whether any row has been returned, I'm not able to do it correctly. What is happening is that the column heading is also being considered as a data and being written to the output file. I want that if there is no data ( excepting the column headings ) the program should terminate. Can anyone help me out of this? Thanks & regards,
    Faisal

    Hi,
    Plz find the code below :
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class JDBC8
         public static void main (String[] args) throws Exception
                        Connection con = null;
                        final String query = "select TNAME,TABTYPE from tab where tname like '%FAZ%'";
                        Statement stmt = null;
                        int ctr=0;
                        int maxColLength = 0;
                        String fileName = "";
                        ResultSet rs = null;
                        FileNameCreater obj = new FileNameCreater();
                        fileName = obj.getFileName();
                        int t = 0;
                        System.out.println("Created file : " +fileName);
                        try {
                             // load the driver
                                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        catch (java.lang.ClassNotFoundException e)
                                  System.err.print("ClassNotFoundException.");
                                  System.err.println(e.getMessage());
                        System.out.println("Connecting to the database. Please wait....");
                        try {
                                       // define the connection URL. establish the connection.
                                       con = DriverManager.getConnection("jdbc:odbc:DSN1","mis","abcdef#0");
                                       if ( con.isClosed() )
                                       System.out.println("Failed to connect to the database. Press enter to continue.");
                                       System.in.read();
                                       else
                                       System.out.println("Connected to the database.");
                                       System.out.println("Processing...Please be patient...");
                                       // create a statement object
                                       stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
                                       // Execute a query
                                       rs = stmt.executeQuery(query);
                                       ResultSetMetaData rsmd = rs.getMetaData();
                                       rs.first();
                                       System.out.println("check 1 = " + rs.getRow());
                                       System.in.read();
                                       int cntr = 0;
                                       String tempStr = "";
                                       String tempLbl = "";
                                       boolean flag = false;
                                       boolean inWhile = false;
                                       rs.beforeFirst();
                                       while ( rs.next() )
                                            System.out.println("entered while");
                                            System.in.read();
                                            tempStr = rs.getString(++cntr);
                                            tempLbl = rsmd.getColumnLabel(cntr);
                                            System.out.println("cntr = " + cntr + " tempStr = " + tempStr + " tempLbl = " + tempLbl);
                                            if ( tempStr == tempLbl )
                                                 flag = true;
                                            else
                                                 flag = false;
                                            inWhile = true;
                                       if ( inWhile )
                                                 rs.beforeFirst();
                                                 FileWriter writer = new FileWriter(fileName);
                                                 BufferedWriter buf_Writer = new BufferedWriter(writer);
                                                 System.out.println("Processing started...");
                                                 int colCount = 0;
                                                 colCount = rsmd.getColumnCount();
                                                 String colLabel = "";
                                                 for ( int x = 1; x <= colCount; x++ )
                                                      colLabel = rsmd.getColumnLabel(x);
                                                      buf_Writer.write(colLabel);
                                                      if ( x < colCount )
                                                           buf_Writer.write("|");
                                                 buf_Writer.newLine();
                                                 rs.beforeFirst();
                                                 // Process the results
                                                 while(rs.next())
                                                 ctr++;
                                                      for (int i = 1; i <= colCount; i++)
                                                           String columnValue = rs.getString(i);
                                                           buf_Writer.write(columnValue);     
                                                           if ( i < colCount )
                                                                buf_Writer.write("|");               
                                                      buf_Writer.newLine();
                                                 buf_Writer.close();
                             catch (SQLException e)
                                  System.err.println("SQLException : " + e.getMessage());
                             finally
                                  try
                                       // Close the resultset, statement and connection objects.
                                            if (rs != null)
                                                 rs.close();
                                            if (stmt != null)
                                                 stmt.close();
                                            if (con!=null)
                                                 con.close();
                                       catch(Exception ex)
                                            System.out.println("Exception encountered: "+ ex.getMessage());
                                  System.out.println("Program completed successfully.");
    } // end of main
    } // end of class

Maybe you are looking for

  • Error -3 / Itunes wont open after updated with Quicktime 7

    I have been having problems with my Quicktimes for over a month. I was unale to take my son to his favortie websites. I was able to disable quicktime as a default, but now two things have happend. I can't open up Itunes, and now I can't hear any soun

  • How do I get rid of printer notifications that don't work?

    I keep getting a notification from Apple about updating my printer driver. ("Would you like to download and install software for "Samsung SCX-4623 Series"?"). When I click OK it searches for the driver but says it can't find it, and that I should try

  • MiniWAS 4,6D

    Hi all: Just wondering if someone could help me with the following? I have recently installed miniWAS4.6D to work with the ABAP Objects book, however when I come to Object Navigator I don't appear to have the Objects List in the top far left hand cor

  • What is the maximum number of builds in Keynote version 6.2?

    What is the maximum number of builds in Keynote version 6.2? If there are any... I'm up to 800 builds and seems to be working great. I'd like to keep adding builds and want to know if anyone has stumbled across a limit and started to have issues. Tha

  • PS CC Generate not visible.

    Hello, I am using ReFlow CC and PS CC. But not visible Generate. http://d.pr/i/D10i