No. Of Rows in a resultset

Is there a method in result which one could use to get the no. of rows in a resultset. I currently get my no. by looping thru the resultset and summing the number of times the loop runs.
Cheers,
Havasen

I don't know if it's driver specific - what can you say what any driver does inside?
But I think, the most common way should be, that the driver does the same like I and others did it formerly in C programs with embedded SQL:
Let the DBMS create a cursor for the query.
Open this cursor - so the DBMS creates a temporary result set inside.
Position that cursor inside this result set (inside he DBMS).
Fetch the actual row.
After finnishing your logic, close the cursor. So the DBMS clears up its temporary result set.
Now what JDBC presents you as a scrollable result set, should be nothing more than an opened cursor, ready to position on ra single row and fetch it, ... and at the end - when you call ResultSet.close() - close the cursor.
So each row can stay inside the DBMS, until you cause JDBC to fetch it. I think, this is, when you position on it, and JDBC does some caching and retrieves a couple of rows together - there are methods to control this to a certain degree, like Statement.setFetchSize().
But the DBMS must hold the cursor and maintain its temporary result set.
So it's not equal if you cause JDBC to retrieve a complete resultset - and for positioning on the last row, it has to retrieve them all, I fear.
As I said - I can't promise that your driver will work this way.
If I would write a JDBC driver, I probably would try it this way. But I haven't yet, and why should I.
That was the explanation.
And to the original question:
For counting the records only, I would never suggest the last() trick, but a simple query on
"SELECT COUNT(*) FROM table".

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.

  • Returning a subset of rows through a ResultSet WITHOUT rownum?

    I am trying to figure out a way to get a subset of rows from a ResultSet (or ResultSet equivalent) without using rownum and without sending all the rows before the requested row over the wire.
    My problem is this: I am not in control of the SQL that is sent to the database. It is autogenerated by a third party tool (TOPLink). Therefore using the rownum solution isn't practical. My steps of operation are:
    1. Get SQL from TOPLink
    2. Pass SQL through a Statement
    3. Get resulting ResultSet
    At this point, I want to say, "Mr. ResultSet, I only want rows 200-250." And I then want Mr. ResultSet to fetch only rows 200 to 250, and no others. I don't want to see rows 1 to 199 coming over the wire.
    Anyone have any ideas? Is this possible at all? Also, if there's a way to do this through the TOPLink mechanisms (ScrollableCursors and ReportQuery objects and whatnot), please do let me know. I have tried using the TOPLink facilities, and sure enough rows 1 to 199 flow across the network.
    Thanks,
    Michael Allen
    [email protected]

    Hi Michael,
    Is there some sort of selection criteria in which you could use return the required 200-250 rows of data? If so, I would embed that into the TopLink query.
    Another option is using the ORDER BY operator. Without order, constructing a query of elements 200-250 twice would not guarentee that they would be the same elements.
    You can also construct your own SQL statement and execute it directly on a TopLink session.
    Darren Melanson
    Strategic Implementation Consultant
    Oracle Canada.
    I am trying to figure out a way to get a subset of rows from a ResultSet (or ResultSet equivalent) without using rownum and without sending all the rows before the requested row over the wire.
    My problem is this: I am not in control of the SQL that is sent to the database. It is autogenerated by a third party tool (TOPLink). Therefore using the rownum solution isn't practical. My steps of operation are:
    1. Get SQL from TOPLink
    2. Pass SQL through a Statement
    3. Get resulting ResultSet
    At this point, I want to say, "Mr. ResultSet, I only want rows 200-250." And I then want Mr. ResultSet to fetch only rows 200 to 250, and no others. I don't want to see rows 1 to 199 coming over the wire.
    Anyone have any ideas? Is this possible at all? Also, if there's a way to do this through the TOPLink mechanisms (ScrollableCursors and ReportQuery objects and whatnot), please do let me know. I have tried using the TOPLink facilities, and sure enough rows 1 to 199 flow across the network.
    Thanks,
    Michael Allen
    [email protected]

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

  • Counting Rows from a ResultSet

    Hi!
    If I retreive some information from a database, say by using:
    ResultSet RS = Stmt.executeQuery("select * from events");How can I get a value for the amount of rows in this ResultSet?
    Thanks!
    Alastair

    Almost everyone, when they first use ResultSet thinks of it as a container with the data rows already in there, and wonders why there's no size method.
    But that's not how they work. A ResultSet, generally, holds only one row at a time. next requests the next row from the database and before next is called the ResultSet doesn't know if another row is going to be available. Indeed the number of rows that qualify for return in the result set may actually change while you are processing it.
    Doing the SELECT COUNT(*) request asks the database for the number of rows that match any criteria in the SELECT, but that number may have changed when you actually retrieve the rows. Someone else may have added or removed rows.

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

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

  • Number of columns of the rows in a ResultSet?

    Hello
    Is there any way to get the amount of columns of the rows in a ResultSet? The values of the columns might be empty, so wasNull() wont work?
    Thanks

    Yes, you can see the number of columns and lots of other info, see ResultSetMetaData. Example:
    ResultSet rs = statement.executeQuery("...");
    ResultSetMetaData rsmd = rs.getMetaData();
    System.out.println("Number of columns: " + rsmd.getColumnCount());Look it up in the API documentation.

  • Counting the rows in a ResultSet

    I am wondering how I could find out the number of rows in a ResultSet after performing a query?

    In case anyone's curious I figured out the problem. The ResultSet needs to be set to move forward AND backward. This is done as follows:
    Statement stmt = conn.createStatement(
                             ResultSet.TYPE_SCROLL_INSENSITIVE,
                                  ResultSet.CONCUR_READ_ONLY);

  • Java.sql.SQLException: No current row in the ResultSet

    Hi All,
    I use JTDS 1.2.
    I get the following error:
    java.sql.SQLException: No current row in the ResultSet.
    when I run the following code:
         public void QueryToCust(){     
              String username = "sa";
              String password = "";
              String url = "jdbc:jtds:sqlserver://localhost:1433/OkyanusPINAR2006;tds=8.0";
              setSQLcode("select * from firma where kod='123'");          
              try{
                   Class.forName("net.sourceforge.jtds.jdbc.Driver");     
              } catch (Exception e){               
                   setErrMsg(e.toString() + " cannot register class.");
                   return;
              Statement stmt = null;
              Connection con = null;
              try{
                   con = DriverManager.getConnection(url,username,password);          
              } catch (Exception e){
                   setErrMsg(e.toString() + " cannot connection!");
                   return;          
              try{
                   stmt = con.createStatement();          
                   ResultSet rs = stmt.executeQuery(sqlCode);               
                   if(rs != null){
                        String name = new String(rs.getString("name"));
                        setCustName(name);     
              rs.close();
                   con.close();
              } catch (Exception e){
                   setErrMsg(e.toString());
                   return;          
              setErrMsg("jdbc: No error!");          
         }This sql code running with msSQL Enterprise Manager SQL tools return to row. But can not run it in java! Why?

    you need to call
    rs.next();

  • How to get the last row in a resultset or query

    Hi All
    Say If I have a complex query which returns a resultset say 15 rows. Now I want to limit the output showing only the last row.
    How can we do this

    Keep in mind Oracle does not keep "row" order as such. Unlike a graphical type db like Access, Oracle will not always give you back the results in order.
    Even if you were to use a sequence, your query is never guaranteed to give back the results in the order you are expecting. You must then give an order by statement to all queries expecting the order.
    Your definition of last row too is vague - if it is in fact the greatest amount, use the inline view suggestion. If you simply want to see the last inserted row, consider adding a last_update_date column inserting the sysdate (by a trigger perhaps). This would then allow you to see the last inserted row.
    Enjoy!

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

  • Trying to get the last row from a resultset

    Hi,
    I'm trying to do a query to postgreSQL and have it return the last updated value, (last row).
    My prepared statement is returning the correct results, but i'm having a problem getting the latest value.
    I'm using a comboBox to drive a textfield, to load the last entered values in depending on which item in the comboBox is selected.
    I've tried a variety of things and most seem to return the first row, not showing the updated values.
    Or, if it does work, it takes to long to load, and i get an error.
    here is the working code;
    Object m = machCBX.getSelectedItem():
    try { PreparedStatment last = conn.prepareStatement("SELECT part, count FROM production WHERE machine = ?",
    ResultSet.TYPE_SCROLL_INSENSITIVE,  //tried both INSENSITIVE and SENSITIVE
    ResultSet.CONCUR_READ_ONLY);
    last.setString(1, String.valueOf(m));
    rs. = last.executeQuery();
    if(rs.isAfterLast) == false ) {
    rs.afterLast();
    while(rs.previous()) {
    String p = rs.getString("part");
    int c = rs.getInt("count");
    partJTX.setText(p);
    countJTX.setText(c);
    }this grabs values, but they are not the last entered values.
    Now if i try to use rs.last() it returns the value i'm looking for but takes to long, and i get:
    Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space I also know using ra.last() isn't the best way to go.
    I'm just wondering if there is another way other than getting into vectors and row count? or am i better off to go with the later?
    thanks
    -PD

    OK, you've got a major misunderstanding...
    The relational database model is built on the storage of sets - UNORDERED sets. In other words, when you hand a database a SELECT statement without an ORDER BY clause, the database is free to return the results in any order.
    Now it so happens that most databases will happen to return data retrieved by an unordered SELECT, at least for a while, in the same order that it was inserted, especially if no UPDATE or DELETE activity has occured, and no database maintenance has occured. However, eventually most tables have some operation that creates a "space" in the underlying storage, or causes a row to expand and have to be moved or extended, or something. Then the database will start returning unordered results in a different order. If you (or other people) never ever ever UPDATE or DELETE a table, then on some databases the data might well come out in insertion order for a very very long time; given human nature and the way projects tend to work, relying on that is a sucker's bet, IMHO.
    In other words, if you want the "most recent" something, you need to store a timestamp with your data. (With some databases, you might be able to take advantage of some non-standard feature to get "last updates" or "row change timestamps", but I know of no such for Postgres.
    While this won't solve your major problem, above, your issue with rs.last is probably occuring because Postgres by default will prefetch your entire ResultSet. Use Statement.setFetchSize() to change that (PreparedStatement inherits the method, of course).

  • 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

  • TS3694 I have the latest update on my iPad. when trying to do a restore iTunes is trying to give me the updat I already have.

    I lost my play list, when trying to use Home Sharing, So I turned Home Sharing off and sync over WI-Fi off, and tried to sync my original play lists back. That did not work. So I decided to do a restore (I need to clean up anyway) I have the latest u

  • The "Adobe PDF" menu choice does not appear on Excel Menu

    I've installed Acrobat 9.1.2 and the "Adobe PDF" menu choice does not appear on the Excel 2000 Menu.  I have uninstalled and reinstalled the Microsoft Office option in PDF Maker with no change.  It does appear on the Word 2000 Menu.  Adobe 8.1.3 show

  • CS6 - 'Smart Guides' aren't vissible

    I have a love-hate relationship with Smart Guides, but I need them.  After installing Illustrator CS6 (Production Suite) on my Mac Pro (2 x Quad-Core Intel Xeon, 12 Gb of RAM) I can't toggle Smart Guides on!  Whether there is a check next to the menu

  • Continual SMB Problems

    I really have searched for the answer to my specific problem but nothing has really satisfied my problem as of yet. Much to the chagrin of everyone I work with, I purchased a Mac two years ago. I had major problems getting my E-mail set up with Entou

  • HOW TO POST J1IEX FOR SERV ENTRY SHEET.?

    Dear All ,                                       User had done a serv entry sheet , against serv P.O in invoice the service is exciseable , pl help me how to post the J1IEX for this serv entry sheet.? item catogary in P.O is d & acctt assignnis P( Pr