Getting # of rows returned in JDBC resultset

Hi,
Is there an easy call to get the number of rows in a resultset?
Right now I want to display en entire record if there's only one and display only a subset of record info if there's more than one.
I ended up doing the following:
while(rs.next()) {
i++);
then I call rs.beforeFirst(); to get back to the beginning of the result set and set my conditionals to operate on the "i" variable I created before.
There must be a rs.maxcount() or something to that effect isn't there? I'm using a JDBC2.0 type 4 postgreSQL driver. It supports Datasourcing, but not much else.
Frank

Hi,
You can do it in two ways,
1. As stated above, you can do it.
For more information,
http://java.sun.com/j2se/1.3/docs/api/java/sql/ResultSet.html
2.You can use a seperate prepared statement that returns nothing but a count of the rows that will be selected. i.e. select count(*) from Table,
Instead of * you can also use any column existing in Table.
Hope this helps.
Best Luck!
Senthil Babu J

Similar Messages

  • Number of rows returned by the resultset is wrong

    Hi All,
    I have pasted the code i used for JDBC. The problem is the number of rows returned by the resultset is 5 times that of the original data. Is something wrong with my code. Can anyone pls point out the mistake I have done if any.
        public ArrayList dataBreakup(String team, int monthNo, int year) {         String sqlDataBreakup = "";         Connection con1 = null;         Statement stmt = null;         ResultSet rs = null;         ArrayList data = new ArrayList();         int noRows = 0;         Calendar cal = Calendar.getInstance();         Calendar cal2 = new GregorianCalendar(cal.get(Calendar.YEAR), monthNo, 1);         int days = cal2.getActualMaximum(cal2.DAY_OF_MONTH);         String start_date = "01-Jan-" + year;         String end_date = days + "-" + monthName[cal2.get(Calendar.MONTH)] + "-" + cal2.get(cal2.YEAR);         System.out.println("START: " + start_date);         System.out.println("END: " + end_date);         databaseConnection dbObject = new databaseConnection();         try {             con1 = dbObject.GetConnection();             stmt = con1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);             sqlDataBreakup = "Select * from EXPENSE_STORE WHERE " +                     "team='" + team + "'AND category != 'Pending PO''s' AND ACCOUNTING_DATE " +                     "BETWEEN to_date('" + start_date + "') AND to_date('" + end_date + "')";             rs = stmt.executeQuery(sqlDataBreakup);                         ResultSetMetaData rsmd = rs.getMetaData();             int numColumns = rsmd.getColumnCount();             data.add(numColumns);             for (int i = 1; i < numColumns + 1; i++) {                 data.add(rsmd.getColumnName(i));             }                        while (rs.next()) {                                noRows++;                 for (int i = 1; i < numColumns + 1; i++) {                     switch (rsmd.getColumnType(i)) {                         case java.sql.Types.NUMERIC:                             data.add(rs.getFloat(i));                             break;                         case java.sql.Types.DATE:                             data.add(rs.getDate(i));                             break;                         default:                             data.add(rs.getString(i));                             break;                     }                                    }                     }             data.add(1, noRows);             rs.close();         } catch (SQLException SQLe) {             System.out.println("DumpData() : SQL Exception" + SQLe.getMessage());             SQLe.printStackTrace();         } catch (Exception e) {             System.out.println("DumpData() : Other Exception");             e.printStackTrace();         } finally {             dbObject.CloseConnection(con1);         }         return data;     }
    Thanks
    Cheers N...

    Only thing i can say is
    try the following
    replace your function by this one and tell us the console output of the same
    public ArrayList dataBreakup(String team, int monthNo, int year) {
            String sqlDataBreakup = "";
            Connection con = null;          
            ArrayList data = new ArrayList();
            int noRows = 0;
            Calendar cal = Calendar.getInstance();
            Calendar cal2 = new GregorianCalendar(cal.get(Calendar.YEAR), monthNo, 1);
            int days = cal2.getActualMaximum(cal2.DAY_OF_MONTH);
            String start_date = "01-Jan-" + year;
            String end_date = days + "-" + monthName[cal2.get(Calendar.MONTH)] + "-" + cal2.get(cal2.YEAR);
            System.out.println("START: " + start_date);
            System.out.println("END: " + end_date);
            System.out.println("START: " + start_date);
            System.out.println("END: " + end_date);
            databaseConnection dbObject = new databaseConnection();
            try {
                con = dbObject.GetConnection();          
                sqlDataBreakup = "Select * from EXPENSE_STORE WHERE " +
                        "team = '"+team+"' AND category != 'Pending PO''s' AND ACCOUNTING_DATE " +
                        "BETWEEN to_date('"+start_date+"') AND to_date('"+end_date+"')";
                   System.out.println("-----------sql starts---------------");
                   System.out.println(sqlDataBreakup);
                   System.out.println("-----------sql ends---------------");
                PreparedStatement pstmt = con.prepareStatement(sqlDataBreakup);
                   pstmt.setString(1, team);
                pstmt.setString(2, start_date);
                pstmt.setString(3, end_date);
                ResultSet rs = pstmt.executeQuery();
                ResultSetMetaData rsmd = rs.getMetaData();
                int numColumns = rsmd.getColumnCount();
                data.add(numColumns);
                for (int i = 1; i < numColumns + 1; i++) {
                    data.add(rsmd.getColumnName(i));
                while (rs.next()) {
                    noRows++;
                    for (int i = 1; i < numColumns + 1; i++) {
                        switch (rsmd.getColumnType(i)) {
                            case java.sql.Types.NUMERIC:
                                data.add(rs.getFloat(i));
                                break;
                            case java.sql.Types.DATE:
                                data.add(rs.getDate(i));
                                break;
                            default:
                                data.add(rs.getString(i));
                                break;
                //data.add(1, noRows);
                   System.out.println("no of Rows : " +noRows );
            } catch (SQLException SQLe) {
                System.out.println("DumpData() : SQL Exception" + SQLe.getMessage());
                SQLe.printStackTrace();
            } catch (Exception e) {
                System.out.println("DumpData() : Other Exception");
                e.printStackTrace();
            } finally {
                dbObject.CloseConnection(con);
            return data;
        }and try running the sql printed on the screen in your db and then let us know the result.
    in this code i have removed some of your code in order to simplify the problem.

  • How to get # of rows in SQL Query ResultSet

    I need to get the # of rows in a sql query resultset so I can create arrays of the size of the # or rows returned. This is how I do it so far. Is there a better way without running the query twice?
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(query);
    while (rs.next())
         i++;     
    aid = new int;
    i=0;
    rs = stmt.executeQuery(query);
    while (rs.next())
         aid[i] = rs.getInt(1);
    Theres actually a few more arrays but for this I just used one to show what I was doing. Notice stmt.executeQuery needed to be called twice, once to get the count to set the size of the array and once to get the values.

    nope - there's no easy way.
    the right thing to do is to iterate through the ResultSet, load its contents into a List of Objects or some other data structure, and close it out right away. You can get the count of rows while you do it. return the contents in the object or data structure for clients to use. you should never be passing a ResultSet around.
    why do you need to know, anyway?
    %

  • How to get the row Count of a ResultSet

    How to get the row Count of a ResultSet

    Hi
    I'v tried rennie1's way ,but I only get zero,my code is:
    rs.executeQuery("select count(*) from t_test");
    if (rs.next()) int rowCount=rs.getInt(1);
    I also tried barni's way ,but the method rs.last() and rs.beforeFirst() throw a same Exception
    I tried another way,the code is:
    while rs.next(){
    // Do nothing ,just move the cursour to the last row
    int rowCount=rs.getRow()
    However,the rowCount still equal zero
    Any help would be greatly apprecite!
    note:
    I get connection by DataSource's JNDI name from client, the Server is Weblogic Server 6, the DBMS is Oracle.

  • Getting the no. of rows returned from the resultset

    Could somebody tell how can I get the count of rows from the resultset object.
    Thanks a lot in advance

    hmmm 20,710 topics and 69,000 odd posts and no one has EVER asked this question before.. it's a miracle....
    or maybe it has been asked and dealt with approx... 11,000 times.
    here is a discussion from 1998 for example http://forum.java.sun.com/thread.jsp?forum=48&thread=83958

  • How to get the row's size of  ResultSet ?

    i can't find a method to return the record number of a ResultSet.
    how can i get it without using the next() method and select count(*) from sometable

    If you use a scrollable ResultSet, you can do something like this:
                   int currRow = rset.getRow();
                   rset.last();
                   int numRows = rset.getRow();
                   if(currRow == 0)
                        rset.beforeFirst();
                   else
                        rset.absolute(currRow);
    [/code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • When I run my query (below) I only get 100 rows returned.

    I am a little rusty with SQL so I think that I must be doing something simple wrong. Here is the query:
    SELECT Tagname, Value, DateTime
    FROM Insql.Runtime.dbo.AnalogHistory
    WHERE "DateTime" > 'February 26 2014 10:30'
    AND "DateTime" < 'February 26 2014 10:50'
    AND Tagname = 'T0201001'
    This is a wonderware plant historical database that collects analog data every 5 seconds.
    No matter the time frame, 5 minutes or 5 hours I get back 100 rows of evenly time spaced data.
    I went into the query options and edited them to no avail. I am sure that I could calculate how mainy rows I think that I should have and select that number but I assumed the given the date range it would figure that out by itself.

    I got the same result running:
    SELECT Tagname, Value, [DateTime]
    FROM Insql.Runtime.dbo.AnalogHistory
    WHERE [DateTime] > 'February 26 2014 10:30'
    AND [DateTime] < 'February 26 2014 12:50'
    AND Tagname = 'T0201001'I am running my query from Microsoft SQL Server Management Studio  10.0.2531.0.I have been running this DB since 2000 (obviously in older versions of SQL).The DB was developed out of corporate and we just add tags through the WonderWare InSQL Historianwe can access the data through several trending applications. I was just teying to directly access the datato do some analsys with the raw data. I did check the Query options in Microsoft SQL Server Management Studioand it didn't appear to help. I was assuming that there was some default limitation but could not locate a setting anywhere.

  • Oracle XMLTable function no rows returned

    I have a following xml document stored in XML type table
    <?xml version="1.0" encoding="utf-8"?>
    <Document xmlns="urn:iso:std:iso:200:tech:xsd:101" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <FIToFICstmrCdtTrf xmlns="urn:iso:std:iso:200:tech:xsd:101">
                                <CreditTx>
                    <PaymentID>
                        <InstrumentId>AAB000001</InstrumentId>
                        <Id>4730 2013-10-23 AAB000001</Id>
                        <TranxId>BULKTTXTDAAB000001</TranxId>
                    </PaymentID>
                </CreditTx>
            </FIToFICstmrCdtTrf>
    </Document>
    And i am trying to select
    I am on Oracle Version 11.2.0.3SELECT payments.txid,
    payments.endtoendid,
    payments. instrid
    FROM payment_load_xml,
    XMLTable('for $i in /Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId
    return $i'
    PASSING OBJECT_VALUE
    COLUMNS
    instrid VARCHAR2(20) PATH 'InstrId' ,
    endtoendid VARCHAR2(20) PATH 'EndToEndId' ,
    txid VARCHAR2(20) PATH 'TxId'
    )payments
    I am getting no rows returned any ideas please

    The document has a default namespace, so you have to declare it :
    SELECT payments.txid, 
           payments.endtoendid, 
           payments. instrid 
    FROM payment_load_xml, 
         XMLTable(
          XMLNamespaces(default 'urn:iso:std:iso:200:tech:xsd:101') ,
           'for $i in /Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId 
            return $i' 
           PASSING OBJECT_VALUE 
           COLUMNS 
             instrid    VARCHAR2(20) PATH 'InstrId' , 
             endtoendid VARCHAR2(20) PATH 'EndToEndId' , 
             txid       VARCHAR2(20) PATH 'TxId' 
    ) payments ;
    and additionally, your paths don't point to anything in the sample document.

  • No rows returned in the BIS views

    I am new to Discoverer. I had connected to Financials Intelligence responsibility using discoverer desktop. When I tried to create a workbook in General Ledger Business Area to display the GL accounts, I get no rows returned message. I get the same message for any kind of report I try to create not only in GL business area but also in any of the seeded business areas provided by the Oracle. I can query it in toad and see the data but it is not retrieved in discoverer. what could be the problem? is there any profile options to be setup for my username or am I missing something?
    Any help is greatly appreciated
    Thanks

    Here's the metalink note for those interested.
    It's basically laying out all the steps to setup the info in Oracle Apps as alluded to by Simon and then perform a complete refresh of the BIS views in the database, bring in the new .eex file for changes, etc.
    Russ
    ===========================================================
    Applies to: Oracle Discoverer - Version: 10.1.2.48.18
    This problem can occur on any platform.
    Oracle Applications 11.5.10.2
    Oracle Applications Concurrent Manager SymptomsUnable to retrieve any data on standard General Ledger (GL) business areas and standard workbooks after migrating the EUL from Discoverer 4.1 to 10.1.2 and upgrading Oracle Applications to 11.5.10.2.
    These same workbooks and business areas worked fine before the upgrade to Discoverer 10.1.2.
    A custom business area and custom workbooks return data, but none of the standard pre-seeded "BIS" or "Financials Intelligence General Ledger (GL) business areas return data when testing in Discoverer Plus, Viewer or Desktop.
    ChangesMigrated the Discoverer EUL and Oracle Application Server environment from Discoverer 4.1.48.08 to 10.1.2.48.18. CauseIncomplete setup of Oracle E-Business Suite and Discoverer environment for Business Intelligence (BIS) and/or Financials Intelligence, including missing profile options for Oracle Applications Administrator and custom Super User responsibility.
    SolutionTo implement the solution, please execute the following steps:
    1. Login to Oracle Applications Systems Administration function as SYSADMIN user and set the profile option as described below:
    a. Profile > System
    b. Check the 'Site', 'Responsibility' and 'Profiles with No Values' checkboxes
    c. Enter "Applications Administration' in 'Responsibility' field
    d. Enter FII: GL BIS Discoverer access (if it does not display the profile option, please try wildcard option "FII%GL%BIS%" )
    e. Then in the next screen, select 'Yes' from LOV under 'Site' and 'Responsibility' column
    f. Save the settings
    g. Again repeat the same steps for custom responsibility "My_Company General Ledger Super User"
    2. Complete/confirm the following steps from Note 313418.1, Section 6, Post Installation Tasks
    a) Step 4. Regenerate your Business Views - done throughNote 313418.1, Section 6, Post Installation Tasks
    a) Step 4. Regenerate your Business Views - done through Oracle Applications Concurrent Manager as SYSADMIN user with the "Business Views Setup" responsibility.
    b) Recommend all steps under 4 and steps under 5
    c) Step 8. Refresh the Discoverer 10.1.2 End User Layer - via SYSADMIN user/responsibility - as described in note
    d) Step 9 -> Need to make sure Applications Administrator responsibility has all
    security and access to the EUL and business areas. Be sure to grant to responsibility
    rather than SYSADMIN user since the "Applications Administrator" responsibility is used to perform Discoverer Administration tasks.
    $ORACLE_HOME/bin/eulapi \
    -CONNECT <EUL schema>/<password>@<db> \
    -GRANT_PRIVILEGE \
    -ROLE "Applications Administrator" \
    -PRIVILEGE all_admin_privs
    $ORACLE_HOME/bin/eulapi \
    -CONNECT <EUL schema>/<password>@<db> \
    -GRANT_PRIVILEGE \
    -ROLE "Applications Administrator" \
    -PRIVILEGE all_user_privs
    AND
    $ORACLE_HOME/bin/eulapi \
    -CONNECT <EUL schema>/<password>@<db> \
    -GRANT_PRIVILEGE \
    - ROLE "Applications Administrator" \
    -BUSINESS_AREA_ADMIN_ACCESS % \
    -WILDCARD \
    -LOG <log file name>
    Note: The above commands need to be in one continuous line. For Unix/Linux, you may separate lines with continuation character "\"
    3. Once all steps have been completed, the standard General Ledger (GL) workbooks and newly created workbooks based on standard GL usiness areas will return data.
    Note: If you are unsure if you are encountering this specific issue, it is always beneficial to test the data via SQL using the same Oracle E-Business Suite user and responsibility.
    The following reference will guide you how to accomplish this:
    Note 279736.1 'How To Run SQL From An Apps Mode Discoverer Workbook In SQL*PLUS'
    ReferencesNote 313418.1 - Using Discoverer 10.1.2 with Oracle E-Business Suite 11i
    Note 279736.1 - How To Run SQL From An Apps Mode Discoverer Workbook In SQL*PLUS
    Keywords'BUSINESS~AREA' 'PROFILES-SYSTEM' 'FII~~GL~BIS~DISCOVERER~ACCESS' 'DISCOVERER~4.1.48.08' 'BUSINESS~VIEWS' 'UPGRADE~TO~11.5.10.2' 'PROFILES-SYSTEM' 'UPGRADE~TO~10.1.2'
    --------------------------------------------------------------------------------

  • How to run a select count(*) with multiple rows returned

    Hi,
    I have to run a select count(*) for different reports.
    1) Select count(*) from table
    where state = 'CA'
    2) Select count(*) from table
    where state = 'NY'
    3) Select count(*) from table
    where state = 'NV'
    Instead of running this query again for 50 times, is there a way for me to just put it in one query and get multiple row returns? Thank you.

    Samantha wrote:
    Hi,
    I have to run a select count(*) for different reports.
    1) Select count(*) from table
    where state = 'CA'
    2) Select count(*) from table
    where state = 'NY'
    3) Select count(*) from table
    where state = 'NV'
    Instead of running this query again for 50 times, is there a way for me to just put it in one query and get multiple row returns? Thank you.select state, count(*) from table group by state order by 1;

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

  • Can we proceed even if no ResultSet Returned In JDBC Sender Adapter ?

    Hi friends ,
                           My scenario  is  JDBC to RFC .  I am reading table using JDBC Sender Adapter  and i am passing values to RFC .
                          If my select Query has not returned  any row then it won't come to Pipeline right ?
                            What i want is
                          <b>  If no rows returned then call one RFC  to insert the remarks .
                            If rows found call another RFC  to insert the values </b>
                           How can i handle the Situtation ?
                          Expecting your reply asap
    Regards.,
    V.Rangarajan

    Hi Rangarajan,
    i answered your question and shown up a solution: If Connection Lost in JDBC or no resultset returned how to handle ?.
    Double postings makes it difficult for all involved people to inform theirselfes about the point of discussion.
    The polling sender adapter is doing nothing, if no rows selected. So how do want to send a message?
    You have to use the JDBC receiver adapter, invoke the message by a job in ERP, for example with a self written RFC or a proxy. You can decide at ERP side, which function module it to be called. Of coz there are other possibilities, for example to put the logic into a business process, but you wont have success with the sender adapter.
    Regards,
    Udo

  • If the result from the stored procedure returns 0 rows I get this error returned:

    If the result from the following stored procedure returns 0
    rows I get this error returned:
    faultCode:Server.Processing faultString:'Variable transfers
    is undefined.' faultDetail:''
    How can I get round this?

    Well if I try this in a cfm page:
    <cfstoredproc procedure="GetTransfers"
    datasource="datasource" returncode="true">
    <cfprocparam type="in" cfsqltype="CF_SQL_VARCHAR"
    value="4">
    <cfprocparam type="in" cfsqltype="cf_sql_date"
    value="12/09/2006 08:42:00">
    <cfprocparam type="in" cfsqltype="cf_sql_date"
    value="12/09/2008 08:42:00">
    <cfprocresult name="transfers">
    I get an error like:
    [Macromedia][SQLServer JDBC Driver][SQLServer]Procedure or
    function 'GetTransfers' expects parameter '@fromdate', which was
    not supplied.
    But this procedure only accepts 3 parameters.

  • How to get all rows that are returned in inner sub query of select statemen

    If a sub query in select statement returns more than one row than how to get all those returned rows in the final
    output of the query .It will be all right if all column's value repeat and that multiple output of inner query comes
    in another column .
    How to get that ?

    As Frank said, you likely want a join, and likely an outer join to replicate the select in the projection. Something like:
    SELECT id,stat, section, USER_ID concerned_person
    FROM table_all,
      left join table2
        on room_id = sectoion and
           sur_role = 'r001'
    WHERE section IN (SELECT code
                      FROM t_area
                      WHERE dept= 'p002')An alternative, depending on where and how you are using the statement would be something like:
    SQL> WITH t AS (
      2    select 1 id from dual union all
      3    select 2 id from dual),
      4  t1 as (
      5    select 1 id, 'One' descr from dual union all
      6    select 1, 'Un' from dual union all
      7    select 1, 'Une' from dual)
      8  SELECT t.id, CURSOR(SELECT t1.id, t1.descr from t1
      9                      WHERE t1.id = t.id)
    10  FROM t;
                      ID CURSOR(SELECTT1.ID,T
                       1 CURSOR STATEMENT : 2
    CURSOR STATEMENT : 2
                      ID DESCR
                       1 One
                       1 Un
                       1 Une
                       2 CURSOR STATEMENT : 2
    CURSOR STATEMENT : 2
    no rows selectedJohn

Maybe you are looking for

  • How to display profit center name in report?

    Hi all, I use report line item KE5Z. Would it be possible to display the Profit Center Name as a column beside Profit center column? I don't know, please help me. Thanks a lot.

  • Only allow the user to add simple files to a page

    I know I can restrict what items that can be added to the page at the page group level but is it possible to do it at page level? I'm using portal 10.1.2. Thanks

  • Two monitors macbook air

    Hey all This is my first post in the forum! I have a 13" macbook air with osx 10.8.4 I have it connected to an external monitor, but I want to use two screens. I currently have displayport to VGA adaptor to connect to one screen, but I have a second

  • HOW TO use OCX controls with Java application

    hi Is it possible to use microsoft Ocx controls in java applications.

  • Integration Directory:404 error

    Hi,gurus:    When I loaded ID with http://<hostname>:50100/dir/start/directory.jnlp,the webpage throwedthe error like " 404   Not Found,The requested resource does not exist ".But i could load IR successfully. I don't know the reason,could you help m