Howto get RowCount of ResultSet

Hello,
is there an intelligent way of getting the rowcount of an resultset?
For now I execute 2 SQLQueries, where the second is just executed to get the amount of rows in this selection, which is a lot of sumb overhead:
ResultSet rs = db.getStatement().executeQuery("SELECT * FROM BOOKS WHERE LOWER(titel) like '%" + searchStr + "%' OR LOWER(autor) like '%" + searchStr + "%' OR LOWER(instrument) like '%" + searchStr + "%' ORDER BY " + orderTableName + ";");
               ResultSet countSet = db.st2.executeQuery("SELECT COUNT(*) FROM BOOKS WHERE LOWER(titel) like '%" + searchStr + "%' OR LOWER(autor) like '%" + searchStr + "%' OR LOWER(instrument) like '%" + searchStr + "%';");
Any ideas howto do this in a better way?
Thank you in advance, lg Clemens

[Standard pre-packaged copy&pasted rant follows]
The really really best way to know the number of rows in a ResultSet: write your application so that you don't need to know it.
To get the number of rows in a ResultSet, loop over the result set with while(res.next()). Read each row into an object. Add each object into e.g. a LinkedList. At the end, you will have the rows nicely converted to objects (which you usually should do anyway). And list.size() will give the number of objects.
There are other ways to get the number of objects, but list.size() is the easy and reliable way. If you don't need the rows converted to objects ...why did you select them in the first place?
Tricks with last()/getRow() sort of work. They read the entire result set into memory (in a memory-inefficient way: the storage that scrollable result sets take is almost certainly more than "real" objects). But you'll need to write the while(res.next()) loop anyway. No point in having the computer do the same thing twice. So last()/getRow() is inefficient and just plain extra silly work.
Still thinking of using last()/getRow()? Bad idea. When you execute a select, the database server doesn't necessarily even know the number of rows you selected (the cursor "materializes" as it is being read). The server will hand rows to the JDBC driver, without being able to tell in advance how many there will be. So the only way getRow() can know how many rows there are is by reading in all of the rows. This consumes time and memory. And you STILL have to write the while(res.next()) loop, so the computer is doing the same work twice and you are writing extra code.
"select count(*) from ..." is another way, but it has a few problems: (1) The query gets executed twice, so it is almost twice as slow. (2) The number of rows can change between the two queries. (3) You'll need to write the while(res.next()) loop anyway, so you'll be doing silly useless extra coding work.
Best Practice: stop needing the number of rows.
Second Best Practice: while(res.next()), create objects, put into a LinkedList, use list.size().
Silly Extra Work And Slowness: last()/getRow() or select count(*).
There may be situations where last()/lastRow() may be reasonable. You need to know how your database implements them and understand the performance implications. Don't even try if you can at all use the better ways.
There is a related question: how do I page database results. That may require "select count(*)" or something, depending on how you want to do it. There is no really perfect universal solution for that question using plain SQL.

Similar Messages

  • How to get rowcount in a query which is built on Infocube

    Hi,
    I would like to show rowcount for a report which is built on Infocube.
    If i have a query on DSO, i would get Rowcount in the query designer but how can we get this same Rowcount if i create a query on Infocube.
    Thanks in advance

    If you want to just know the number of records without the need to offer this to users in a query, then use transaction LISTCUBE.
    Make you "Field Selection for Output" via the button to tick the characteristics by which you want to count the number of entries and tick the box "Output number of hits" in the settings section of the selection screen, clear the "Max number of hits" field to make sure you get all rows in your result. On the result list the field counter shows the number of entries.
    Best,
    Ralf

  • HOWTO Get the text of "combo box" and "labe" controls with JavaAccessBridge

    HOWTO Get the text of "combo box" and "labe" controls with JavaAccessBridge.
    Please help,
    I'm trying to use the Java Access Bridge (JAB) 2.1 to get the text in Java Applet controls. I've been able to use the sample code in AccessInfo.cpp sample that comes with JAB to get text from "text" controls in a Java Applet. To clarify, I am referring to the "role" in the AccessibleContextInfo struct being set to "text" or "combo box" or "label".
    The problem is, when I use the AccessInfo.cpp sample to get text from a "combo box", the accessibleText data member comes back as FALSE, and thus any of the JAB text functions like GetAccessibleTextInfo fail to get any text information from "combo box" or "label" controls.
    I've also tried GetCurrentAccessibleValueFromContext on the "combo box" and "label" controls, but the text returned is empty.
    Can anyone help?

    I have new information in regards to this issue. A contact from Sun did get to me in email and relayed that that "label" objects store their text in the "name" data member of the AccessibleContext structure. This was a big help.
    But I'm still stuck trying to get information from "combo box" and other controls, like "push button". The contact said, the Java Access Bridge does not provide all the information because it is already implemented by other interfaces like AccessibleComponent, AccessibleAction, or AccessibleSelection. The contact did not allude to whether these opther interfaces can be used along side the Java Access Bridge or not. So, I'm left a step closer to the goal, but still stuck without the full solution.
    Can one take the Java Access Bridge functions, like say those used in the Ferret sample, and close the gap to get text back from "combo box", "push button", and other controls by using some other API in conjunction?

  • How to get rowcount of VO on .vm file?

    how to get rowcount of VO on .vm file?

    The JSF expresion is:
    #{bindings.<iteratorName>.estimatedRowCount}
    In JHeadstart, iterators are named after the group suffixed with "Iterator", so in the .vm you can use the folloqwing:
    #{bindings.${JHS.current.group.name}Iterator.estimatedRowCount}
    Steven Davelaar,
    JHeadstart Team.

  • Rowcount and resultset check - Message Mapping

    Hi Experts,
    If I don't get the result for the requested value for the synch webservice -> JDBC scenario(without BPM), I have to return "No records found" as a response.
    Below, I have mentioned the Source and Target message Type structure.
    Source Message Type:
    1. JDBC_response
    1.1. STATEMENT_response
    1.1.1. row
    1.1.1.1. EmpId
    1.1.1.2. EmpName
    1.1.1.3. Address
    Target Message Type
    1. SOAP_Response
    1.1.RESPONSE
    1.1.1.row
    1.1.1.1. EmpId
    1.1.1.2. EmpName
    1.1.1.3. Address
    1.1.2 Error Description
    1. What function we have to use in the userdefined function to find the rowcount or to do the resultset check?
    2. If the rowcount is zero, then I have to return the Error Description as a response. Where to mention the Error Description field. It should be under <b>row</b> or ?
    Regards
    Sara
    Message was edited by:
            Sara D

    Sara,
    Please try the below and let us know the feedback.
    Mapping for Row
    http://www.flickr.com/photo_zoom.gne?id=776959840&size=o
    Mapping for Error-Description
    http://www.flickr.com/photo_zoom.gne?id=776959924&size=o
    Results
    http://www.flickr.com/photo_zoom.gne?id=776959934&size=o
    Map the EmpID,EmpName,Address direct mapping from source.
    The logic is , if there is no response rows then it will give the Error Description alone. Similarly if there is resposnse row it won't give the Errordescription. Kindly have a look and let me know whether it matches ur reqmt.
    Best regards,
    raj.

  • What's with the slow gets from my ResultSets?

    I have two databases, an Omnis and a MySQL. I'm trying to copy the data from the Omnis into the mysql, but the getXXX(int i) methods acting on my ResultSet are LUDICROUSLY slow... to transcribe a meager 2660 entires (with 15 columns) takes a staggering 25.3 minutes! Now, what's interesting here is Microsoft Access can have the data in about 3 seconds. Same thing applies when moving from MySQL to access or one MySQL database to the other.
    I am forced to assume that the problem lies with the ResultSet object that the JDBC:ODBC bridge that I'm using to access Omnis from Java. It's also confirmed that the culprits are the get methods, as I can iterate through the entire ResultSet with successive calls to rs.next() and get all the way through it in a couple seconds so long as there are no getXXX() methods in the while loop. Is this problem surmountable? What gives? O_o
    thanks in advance.

    It's not the JDBC-ODBC bridge either... as I can pull data from Omnis > Access > MySQL in about 1/1000th of the time it takes me to go from Omnis > MySQL.

  • Howto get info about a structure !?

    Hi,
    I found a structure with field: ADRC_STRUC - REMARK
    I need to know what table it takes it's data from. Howto ?
    I tried the "Where-Used-List" ... but its not simple
    I want to see the SELECT INTO clause... i belive...
    //Martin
    Message was edited by: Martin Andersson

    Hi Martin,
    This is what I typically do, if I need to find out what table(s) that a given structure ultimately points to.
    1. As suggested by others here, debugging is one option.
    2. Go to SE12, give the structure name, do a where used in programs, tables and function module interfaces. You may end up in getting a lengthy list but you need a good process of elimination to get to the tables. If the structure is used in a table as an INCLUDE or APPEND structure, well and good. But if it is used in a program or a function module interface, I would go to the code and see where the structure is getting filled and with what information. If you could continue to follow this trace, to the main program where the data declarations are at, you will find the tables that are defined. Sometimes searching for a 'Select' statement could lead you to the table.
    Though it sounds cumbersome, most often, I could get my answer and in a quick time.
    Hope this helps,
    Srinivas

  • Trying to get rows to ResultSet with CallableStatement and stored functio

    Hello!
    I'm using JDBC with Oracle XE 11g2, driver ojdbc6.jar (Oracle Database 11g Release 2 (11.2.0.3) JDBC Drivers, JDBC Thin for All Platforms) from oracle.com
    I've got a table
    CREATE TABLE ORGANIZATIONS
    CODE VARCHAR2(4),
    DESCRIPTION VARCHAR2(255)
    And I'm trying to get all organizations into ResultSet using CallableStatement with stored function:
    CallableStatement cs = connection.prepareCall("{? = call FN_GET_ROWS}");
    cs.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
    cs.execute();
    I've created two types:
    CREATE OR REPLACE
    TYPE TEST_OBJ_TYPE AS OBJECT (
    CODE VARCHAR2(4),
    DESCRIPTION VARCHAR2(255)
    and
    CREATE OR REPLACE
    TYPE TEST_TABTYPE AS TABLE OF TEST_OBJ_TYPE
    and my function is
    CREATE OR REPLACE
    FUNCTION FN_GET_ROWS RETURN TEST_TABTYPE AS V_Test_Tabtype Test_TabType;
    BEGIN
    SELECT TEST_OBJ_TYPE(A.CODE, A.DESCRIPTION)
    BULK COLLECT INTO V_Test_TabType
    FROM
    (SELECT CODE, DESCRIPTION
    FROM ASM.ORGANIZATIONS
    ) A;
    RETURN V_Test_TabType;
    END;
    but when I run my program I've got error:
    P LS-00382: expression is of wrong type
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored

    It doesn't look like your PL/SQL Function is returning a REF CURSOR to me. It looks like you are returning a PL/SQL Index-By table of Objects.
    Regards,
    Mark

  • How to get rowcount from a Clob

    Hi,
    Is it possible to get a rowcount from a clob, without writing a loop to iterate/count each row?
    I'm working on a CSV extract procedure, which has been passed a Clob parameter and I just need to extract its rowcount.
    I was expecting a useful function to exist, but it seems not?
    Thanks in advance

    PD81 wrote:
    Okay, if you want to be pedantic about wording:
    How do I get a “Line Count” from a clob?
    I don’t understand the obsession on this forum of responding to criticise a question , whilst adding no value towards an answer, when it’s plainly clear what the question is aiming to achieve.
    I'm not being critical or pedantic.
    The same applies, there's no such things as "lines" in a clob.  A clob is just a series of characters.  As I said it doesn't contain rows, lines or any such structure.
    If you want to search a clob for certain things, you need to be looking at the characters within it.
    So, now you say you want "lines" rather than rows, but what constitutes a "line"?  Is it a chr(10) character?  Is it a chr(13)||chr(10) pair of characters?  Is it some other character such as a ";" or whatever.
    The point is, if you want to get a specific answer, you have to be specific about the requirements.
    A CSV file is just a "Character Seperated Values" file, so what consitutes a row or line in that file (in a clob or physical file) is likewise just as ambiguous.
    How can people supply you with an coded answer to something when the requirements are ambiguous?
    You stated "I was expecting a useful function to exist", and the point is, that why should a function exist to count rows or lines or whatever, when a CLOB, by it's very nature is not a structured data type.  The functions that do exist for CLOB's such as INSTR, SUBSTR, REPLACE etc. are the functions appropriate to a clob, so you have to use those.

  • How to get both, the ResultSet and Output (return value) from Oracle Stored Procedure

    Hi! I am doing a conversion from MSSQL to Oracle with C++ and MFC ODBC. Any comment is appreciated!! I have Oracle 8i and Oracle ODBC 8.1.6 installed.
    My question is how to retrieve the return value AND ALSO the resultSet at the same time by using Oracle function without modifying my souce codes (except puttting mypackage. string infron of my procedure name, see below).
    -- My source code in C++ with MSSQL ....
    sqlStr.Format("{? = call ListOfCustomers(%i)}", nNameID);
    RcOpen = CustomerList.Open(CRecordset::forwardOnly, sqlStr, CRecordset::readOnly );
    Where CustoemrList is a Crecordset object...
    IN DoFieldExchange(CFieldExchange* pFX) I have ...
    //{{AFX_FIELD_MAP(CQOSDB_Group)
    pFX->SetFieldType(CFieldExchange::outputColumn);
    RFX_Long(pFX, T("Name"), mCustoemrName);
    //}}AFX_FIELD_MAP
    // output parameter
    pFX->SetFieldType( CFieldExchange::outputParam );
    RFX_Int( pFX, T("IndexCount"), mCustomerNumber);
    -- m_CustomerNumber is where i store the return value!!!
    -- In Oracle Version, i have similar codes with ...
    sqlStr.Format("{? = call mypackage.ListOfCustomers(%i)}", nNameID);
    RcOpen = CustomerList.Open(CRecordset::forwardOnly, sqlStr, CRecordset::readOnly );
    -- I have oracle package/Body codes as following...
    create or replace package mypackage
    as
    type group_rct is ref cursor;
    Function listgroups(
    nameID NUMBER ,
    RC1 IN OUT Mypackage.group_rct ) return int;
    end;
    Create or replace package body mypackage
    as
    Function listgroups(
    NameID NUMBER ,
    RC1 IN OUT Mypackage.group_rct )return int
    IS
    BEGIN
    OPEN RC1 FOR SELECT Name
    from Customer
    WHERE ID = NameIDEND ListGroups;
    END
    return 7;
    END listgroups;
    END MyPackage;
    Ive simplified my codes a bit....
    null

    yes, it is exactly what i want to do and I am using Oracle ODBC driver.
    I tried using procedure with 1 OUT var fo numeric value and the other IN OUT ref cursor var instead of function, but error occurs when I called it from the application. It give me a memory ecxception error!!
    sqlStr.Format("{? = call ListOfCustomers(%i)}", nNameID);
    RcOpen = CustomerList.Open(CRecordset::forwardOnly, sqlStr, CRecordset::readOnly );
    it seems to me that the ? marker var is making all the trouble... can you please give me any more comment on this?? thanks!
    null

  • How to get values from resultset when using subquery???

    Hi ,
    I have a problem in executing sql query from java.
    I am executing an sql query which return a intersection of values from 3 tables.
    Here is the query I am using
    select id from dps_user where id in (select b.id from dps_user b,laserlink c
    where c.userid='univ.'||b.login and c.status in(1,3,8,9,10)
    intersect
    select b.id from dps_user b,laserlink c
    where c.userid=b.login and c.status in(1,3,8,9,10)).
    this query is working fine from sql .
    when I am trying to excute the same query from java nothing is coming into resultset.
    String ISP_AND_EMAIL="select id "+
                             " from dps_user where id in (select b.id from dps_user b,laserlink c "+
                                  "where c.userid='"+"univ.'"+" ||b.login and c.status in(1,3,8,9,10)"+
                                  " intersect "+
                                  " select b.id from dps_user b,laserlink c"+
                                  " where c.userid=b.login and c.status in(1,3,8,9,10))";
              System.out.println(ISP_AND_EMAIL);
              rs=stmt.executeQuery(ISP_AND_EMAIL);
    How to use concatinate string (|| ) in java.
    can anyone help to retrieve the values from this resultset...
    Thanks

    concatnation is done using + in java.
    I am doubtful about the following line where there may be error
    "where c.userid='"+"univ.'"+" ||b.login and c.status in(1,3,8,9,10)"+
    I don't know if the univ. is a string or some variable.I need more clarification on this line,then i may help u.
    thx

  • Howto get informations from theme

    Hi,
    I need to get some value from portal theme(e.g. some Background color of Groups). Now I now how to get theme:
    ILAFService iLAFService = (ILAFService)request.getService(ILAFService.KEY);
    IThemeInfo theme = iLAFService.getCurrentTheme(request);
    but now I dont know what should I do now. When I tried to debug, i found out that theme is of class LAFService@ThemeInfo but i am not able to cast to this class(still getting NoClassDefFoundError, what should i add to portalapp.xml??). Is there any easy way how to find out that informations from theme? (i tried to decompile theme editor, but i get lost in the beggining of the code ).
    thnaks
    JJ

    Hi JJ,
    first of all the LAFservice (Look and Feel Service) is no public API. Furthermore it has only knowledge about themes and their versions.
    The service which knows about parameters is the DesignService residing within the Portal application com.sap.portal.themes.designservice but also this service is no public API.
    Feel free to send a feature request to Enterprise Portal product management.
    Regards,
    Timo

  • Howto get rid of duplicates in iTunes but keep albums complete

    I try to get rid of duplicates in iTunes but came across the following problem:
    In File -> display duplicates tons of duplicates show up, but when I delete one file the entry is the itunes-library is deleted as well and I will miss this song in that specific album.
    Is there a solution to refer to 1 file on disk with multiple entries in my library, to keep my albums complete with the correct ID3-tags (meta-data) and get rid of duplicate files on disk. This would save me a lot of space on disk.
    Or is the correct way of avoiding copies of files in iTunes, to drag-in the file once and link with various album-playlists to it? Then you still missing the possibility of saving meta-data of those playlist-links, right?

    iTunes does not have the ability to show just one file in multiple albums. So you'll have to keep the multiple files for multiple albums.

  • Problem to get count from resultset with select count(1) like query

    Hi,
    The snippet of code is like this ...!
    preparedStatement = connection.prepareStatement("select count(1) as count from acf_users where acf_user_name like ? and acf_user_password like ?");
    preparedStatement.setString(1,stringUsername);
                   preparedStatement.setString(2,stringPassword);
                   resultSet = preparedStatement.executeQuery() ;
                   System.out.println("The ResultSet Count checkUser() : "+resultSet.getString("count"));
                   preparedStatement.close();
    But there is a SQLException like :
    java.sql.SQLException: ResultSet.next was not called
    I want to extract and check the count in the program..
    Does anyone has the solution, comments on this.
    Thanks in Advance,
    -Sachin

    Thanks a lot to have a look on it :
    I got the solution on it as :
    preparedStatement = connection.prepareStatement("select count(*) as total from acf_users where acf_user_name like ? and acf_user_password like ?");
                   preparedStatement.setString(1,stringUsername);
                   preparedStatement.setString(2,stringPassword);
                   resultSet = preparedStatement.executeQuery() ;
    resultSet.next();
                   System.out.println("The ResultSet checkUser() : "+resultSet.getInt("total"));
    The important line is :
    resultSet.next()
    Thanks once again,
    Sachin !

  • How do I get an updateable ResultSet ?

    Using Oracle 8.1.7 JDBC libs.
    My code reads thus:
    Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = stmt.executeQuery("select * from my_table");
    rs.moveToInsertRow();
    .. yet I see this when I run it:
    java.sql.SQLException: Invalid operation for read only resultset: moveToInsertRow
    Any pointers?
    Thanks,
    - Michael

    I'm partial to this series:
    After Effects basics tutorials by Andrew Devis
    The subject matter is very clearly-defined by topic.
    And AE shouldn't up & quit on you... but you haven't breathed a word about your system or your AE version.  Please share.

Maybe you are looking for

  • Create vendors in FI system from HR master records of the employee

    Hi,    I need a help. I have tried executing the tcode PRAA i.e the program RPRAPA00  to create a vendor from HR master data. I have maintained all the required information: Actions (Infotype 0000) Organizational Assignment (Infotype 0001) Personal D

  • How to get active monitor-Multiple monitors connected to a single machine.

    Hi, How to get the id of active graphic device, in case of multiple graphic devices connected to a single machine(Multi-headed display/ multi headed nodes) using Swing. Prashanth.

  • Transferring pictures not on camera roll to Macbook Pro-HELP!

    Hello everyone, A year ago or so my harddrive on my Macbook Pro unmounted and I lost everything.  Well before that happened I had uploaded thousands of pictures to my Ipad 2 and so those are pictures not on the camera roll but in I guess a different

  • Stub generation problem with the wsdl file

    Hi all I'm trying to write a simle webservice client based on JAX. My webservice is working fine I've tested it with a standalone app. In my webservice I'm using complex type. Problem is that i can't generate properly stubs. This is a msg I'm getting

  • Text issue with Chinese Windows XP

    Hello, When installing a distribution made with the english version of CVI 2010 on a PC with Windows XP in Chinese I have an issue with some caracters like µA or ° (see below) What could be the reason of this behavior and could I solve it?.