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
}

Similar Messages

  • How to get number of rows return in SELECT query

    i'm very new in java, i have a question:
    - How to get number of rows return in SELECT query?
    (i use SQL Server 2000 Driver for JDBC and everything are done, i only want to know problems above)
    Thanks.

    make the result set scroll insensitve, do rs.last(), get the row num, and call rs.beforeFirst(), then you can process the result set like you currently do.
             String sql = "select * from testing";
             PreparedStatement ps =
              con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
             ResultSet rs = ps.executeQuery();
             rs.last();
             System.out.println("Row count = " + rs.getRow());
             rs.beforeFirst();~Tim
    NOTE: Ugly, but does the trick.

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

  • 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 number of rows and columns in a two dimensional array ?

    Hello,
    What would be the simplest way to get number of rows and columns in a two dimensional array represented as integers ?
    I'm looking for another solution as For...Each loop in case of large arrays.
    Regards,
    Petri

    Hi Petri,
    See a attached txt file for obtaining two arrays with upper and lower index values
    Regards
    Ray
    Regards
    Ray Farmer
    Attachments:
    Get2DArrayIndex.txt ‏2 KB

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

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

  • Get number of rows in ResultSet object

    Can anybody guide me on how to get the total number of rows in a result set object without iterating through all rows? Thanks.

    Hi Soon,
    You mention that you want to get the row count without iterating through the "ResultSet". I don't know what database you are using, but I want to inform you that with my Oracle 8i (8.1.7.4) database, using JDK 1.3.1 and the matching JDBC (thin) driver, the implementation of the "last()" method (that others have recommended that you use), actually iterates through the whole "ResultSet".
    What I do is first execute a "SELECT COUNT(1)" query (using a literal "1") to get the number of rows -- this is much faster than executing the "last()" method.
    Then I execute my actual query.
    Hope this helps you.
    Good Luck,
    Avi.

  • 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 get number of rows

    Hi!
    Can someone tell me how to obtain the number of rows returned by a query?
    I tried to use getFetchSize() but it seems to always return 0 for my query.
    THANKS in advance!
    ResultSet testRS = Stmt.executeQuery(testStmt);
    int size = testRS.getFetchSize();
    System.out.println("size = " + size);
    Wo Lay

    To get the number of rows returned, you have to loop
    through the result set, or do a "select count" (which
    is more efficient since it doesn't have to pass the
    rows across the network) ...Looping around the entire result set is not very performance efficient. Then agin if you use count (*) you actually execute an extra query.
    The best thing you can do is:// assume res is your result set.
    res.last();
    int rows = res.getRow();This way you only have to execute one query and you don't really need to loop around the entire result set. Of course you will have to have a scrollable result set, if this is supported by your DB.
    Hope that helped.
    afotoglidis

  • How to get number of rows in tableview

    Hello,
    Could anybody help me on how to get the number of rows in a tableview? Sort of using DESCRIBE TABLE in classic ABAP.
    Thanks,
    Ricky

    There is an attribute of the class CL_HTMLB_TABLEVIEW named
    ROWCOUNT.
    Inside an event u need to get this info use this code:
    Replace 'Monitor'  for the ID of your tableview
    DATA: tv TYPE REF TO CL_HTMLB_TABLEVIEW,
          r_count  type i,
          tv ?= CL_HTMLB_MANAGER=>GET_DATA(
          request = runtime->server->request
          name = 'tableView'
          id = 'Monitor' ).
          IF tv IS NOT INITIAL.
            DATA: tv_data TYPE REF TO CL_HTMLB_EVENT_TABLEVIEW.
            tv_data = tv->data.
            r_count = tv_data->rowcount.
          ENDIF.

  • Resukt:Get number of rows from 3 different table...?

    Hi All,
    I need to find out number of rows from 3 different table for the same conditions. Instead of writing 3 queries, is it possible to get it thru one query?
    For example, i need to find out number of rows in tables where name = 'Ameet' from 3 different table, i will end writing 3 queries.
    1. select count(1) from table_a where name = 'Ameet';
    1. select count(1) from table_b where name = 'Ameet';
    1. select count(1) from table_c where name = 'Ameet';
    Is it possible to write a single query to get result of all above 3 queries?
    result:
    table_a table_b table_c
    34 44 2

    One way:
    SELECT      (SELECT     COUNT(*) AS CNT FROM TABLE_A WHERE name='Ameet') AS TABLE_A
    ,     (SELECT     COUNT(*) AS CNT FROM TABLE_B WHERE name='Ameet') AS TABLE_B
    ,     (SELECT     COUNT(*) AS CNT FROM TABLE_C WHERE name='Ameet') AS TABLE_C
    FROM DUALIf you want the total:
    SELECT     SUM(CNT)
    FROM
         SELECT     COUNT(*) AS CNT FROM TABLE_A WHERE name='Ameet'
         UNION ALL
         SELECT     COUNT(*) FROM TABLE_B WHERE name='Ameet'
         UNION ALL
         SELECT     COUNT(*) FROM TABLE_C WHERE name='Ameet'
    )

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

  • 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

Maybe you are looking for

  • How to include components into mxml file?

    I have an mxml file with multiple states and it is getting quite large. I would like to divide these states into their own components. How can i include these into the mxml file? Thanks!

  • Messages not being marked as Read on IMAP account on iMac

    I use the Mail application on my iMac to read my Gmail. I have it set up as IMAP, and it has worked very well for a long time. Recently, however, I noticed that if I read my mail on my iPhone, or my work computer (both of which have the correct IMAP

  • Material based sales report

    Experts what is the standard report for sales report( material based ) for particular period . Regards

  • Facebook-Problem in Mountain Lion

    The Facebook-button in Notification Center doesn't work at all. Twitter is working fine but Facebook doesn't work. If I push the Post-button nothing happens. It's the same when I use the share-button in Safari: Twitter works, Facebook doesn't do anyt

  • Can't get hyperlinked text in podcast descriptions

    Hello, I have 2 podcasts in iTunes.One has hyperlinked text in the episode descriptions on the Apple podcast app and the other doesn't. My show that doesn't is The Ultimate Health Podcast - http://ultimatehealthpodcast.com I use the Blubrry plugin fo