Can i count row from ResultSet ?

I would like to count row from ResultSet for
take it into my array object because i must know number of row before create array object.
Example:
ResultSet rset = stmt.executeQuery("select * from user ");
/*i = amount of ResultSet*/
User[] user = new User;
int l=0;
while (rset.next()){
user[l] = new User();
user.name = rset.getString(1);
l++;

Hi,
As per my knowledge there is no method by which you can get the count of items in a resultset directly. You will have to loop through the reseltset and set a variable for count. In your specific case I would advise you to use a Vetor instead of an array so that you need not bother about the size.
ResultSet rset = stmt.executeQuery("select * from user ");
Vector user = new Vector();
while (rset.next()){
user.addElement(rset.getString(1));
Now you will have a Vector that holds the user info. To retrieve the user info loop through the Vector.
for (int i; i<user.size(); i++){
userName = user.elementAt(i);
Hope I was of some help.
cheers!!!
Nish

Similar Messages

  • Count rows from several tables

    hello,
    im trying to count row from multiple tables
    for example i need the select statement to produce the following
    table_name count
    table1 5
    table2 6
    table3 3
    i came up with the following script but it counts the number of tables i have
    select object_name, (select count(*) from user_tables where table_name = object_name) from all_objects
    where object_type = 'TABLE'

    Manik wrote:
    May be possible:
    Check this:
    SELECT table_name,
    TO_NUMBER (
    EXTRACTVALUE (
    xmltype (
    DBMS_XMLGEN.getxml ('select count(*) c from ' || table_name)),
    '/ROWSET/ROW/C'))
    COUNT
    FROM (select * from all_tables where table_name in ('TABLE1','TABLE2'))
    WHERE owner = 'SCOTT';Cheers,
    Manik.Awesome Manik... Just too good. Thanks.
    I wish i could have given you the 'Correct' points. ;-)
    Can you please explain the logic in brief? Will be helpful for everybody to understand...

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

  • Any way to count rows from function

    I have the function: pkgcustomer.get(id).
    To count the rows from this function I do:
    select count(*)
    from
      (select pkgcustomer.get(2)
      from dual);So, this gives me 1.
    The id '2' exist
    When I give an id that does nog exist (for example 5999), I also get '1' for the rows he count.
    Can someone help me to get the correct count from a function?
    I also did:
    OPEN c_testresult FOR 'SELECT pkgcustomer.get(2) FROM DUAL;';
              LOOP
                FETCH c_testresult INTO rec_testresult;
                EXIT WHEN c_testresult%NOTFOUND; 
                l_counter         := l_counter + 1;
              END LOOP;
              l_testresult        := to_char(l_counter);
            CLOSE c_testresult;I hope that someone can help me...
    Regards

    > And what if I do the function: pkgcustomer.get(5999)? 5999 is not an existing ID, so this
    should me give 0, but when I do: select pkgcustomer.get(5999) from dual, I also get 1.
    Can you count?
    Okay then. The function returns a value. You are counting the number of values the function returns, right?
    Q. The function returns the number zero. How many values does it return?
    A. One!
    Q. The function returns the number one. How many values does it return?
    A. One!
    Q. The function returns the number 7293273948438727632192378643 . How many values does it return?
    A. One!
    Now if you still fail to grasp this, I seriously suggest you rethink the career choice you've made. Not everyone can be software developers, just like not everyone can be scientists, firefighters, chefs etc.

  • How can I display data from ResultSet to a component like jLable and JTable

    hi there
    My code as shown below
    boolean fillTable(int type){
            try{
                //model.setRowCount(0);
                if(type == 1){
                    System.out.println("line 1");
                    model = new DefaultTableModel(new Object [][] {   },
                            new String[] { "\u1200 Code", "Description" });
                    System.out.println("line 2");
                    while(lookup.rs2.next()){
                        System.out.println("line in while");
                        model.addRow(new String[] { lookup.rs2.getString("code"),
                            "\u1201 " + lookup.rs2.getString("amdescription")});
                          //System.out.println("While : " + lookup.rs2.getString("code") + " " +
                            //      lookup.rs2.getString("amdescription"));
                    lookup.rs2.last();
                    String str;
                    str =  new String (lookup.rs2.getString("amdescription"));
                    jLabel2.setText(str);
                    System.out.println("line 3");
                    tblLookup.setModel(model);
                    System.out.println("line 4");
                else if(type == 2){
                    System.out.println("line else if 1");
            }catch(Exception ex)    {
                System.out.println("Exception @ MilLookupDisplay fillTable : " + ex.getMessage());
                return false;
            return true;
        }I can read from access db and put the resultset on rs2 , it works fine
    my problem is when I try to display the data ( which is amharic unicode character ) on jTable and jLabel as shown it displays '???'
    besides I have checked the font by giving unicode like '\u1200' on both component displays it well
    so is there something to do before trying to display unicode characters from resultSet
    please I ' m waiting
    thanks a lot

    http://forum.java.sun.com/thread.jspa?threadID=5153938

  • Count rows from multiple tables using SQL only

    Hi, I know this has probably been answered before, but I couldn't find the answer anywhere. Please help.
    I'd like count(*) [rows] for all tables in database using SQL only - no PL/SQL
    The result should be something like:
    Table RowCount
    DBA_TABLES 1000
    DBA_USERS 50
    etc.
    Thanks!

    offcource write this script:
    create or replace procedure count_tables (ip_schema VARCHAR2)
    is
    lv_owner VARCHAR2(100);
    lv_table_name VARCHAR2(100);
    lv_sql_statement VARCHAR2(2000);
    lv_count_table NUMBER;
    CURSOR c1 IS
    SELECT owner, table_name
    FROM all_tables
    WHERE owner = ip_schema
    ORDER BY table_name;
    begin
    dbms_output.put_line ('+--------------------------------------------------------------------+');
    dbms_output.put_line ('¦ | | ¦');
    dbms_output.put_line ('¦ Schema Name | Table Name | Number of Rows ¦');
    dbms_output.put_line ('¦ | | ¦');
    dbms_output.put_line ('¦------------------------------------------------------------------¦');
    OPEN c1;
    LOOP
    FETCH c1 INTO lv_owner , lv_table_name;
    EXIT WHEN c1%NOTFOUND;
    lv_sql_statement := 'SELECT count(*) FROM ' || lv_owner || '.' || lv_table_name;
    EXECUTE IMMEDIATE lv_sql_statement INTO lv_count_table;
    IF lv_count_table > 0 THEN
    dbms_output.put_line ('| '||rpad(lv_owner, 14, ' ')||'| '|| rpad(lv_table_name, 32, ' ')||'| '|| rpad(lv_count_table, 16, ' ')||' |');
    -- dbms_output.put_line ('|---------------|---------------------------------|------------------|');
    END IF;
    END LOOP;
    CLOSE c1;
    dbms_output.put_line ('+--------------------------------------------------------------------+');
    exception
    WHEN OTHERS THEN
    dbms_output.put_line ('owner: '||lv_owner||' - table: '||lv_table_name||' - '||sqlerrm);
    end count_tables;
    set serveroutput on size 1000000
    exec count_tables
    drop procedure count_tables;

  • Record working time: can't copy row from worklist for previous week

    When copying a row from worklist to recorded work time for previous week the following error happen.
    com.sap.tc.webdynpro.modelimpl.dynamicrfc.WDDynamicRFCExecuteException: Access with ZERO object reference not possible., error key: RFC_ERROR_SYSTEM_FAILURE
        at com.sap.pcuigp.xssfpm.java.MessageManager.raiseException(MessageManager.java:102)
        at com.sap.xss.hr.cat.record.blc.RfcManager.rfcExecute(RfcManager.java:470)
        at com.sap.xss.hr.cat.record.blc.RfcManager.rfcCopyWorklist(RfcManager.java:378)
        at com.sap.xss.hr.cat.record.blc.wdp.InternalRfcManager.rfcCopyWorklist(InternalRfcManager.java:191)
        at com.sap.xss.hr.cat.record.blc.FcCatRecordInterface.onCopyWorklist(FcCatRecordInterface.java:616)

    If I recall correctly, the Windows clipboard system allows the developer to place different types of data in the clipboard, and convert between them. It is often possible, for example, to paste formatted text as plain text and so on. Large amounts of data are sometimes stored as "links" back to the producing program, so that it can transfer data directly.
    Now this is just a guess, but when you select all with Ctrl+A, there's a chance that Skype in fact puts all the information about the whole message into the clipboard, including its metadata such as time, sender, etc. Dragging would just select the text.
    If the receiving program cannot interpret the metadata, and the plain-text version is not also stored in the clipboard, then pasting would fail.
    Again, as I say, this is just a guess. We would have to get confirmation from the Skype developers as to whether this is true.
    Have you tried pasting into different programs? (Word, plain text editor, Powerpoint...) If one of them can accept the clipboard contents then we may get a further clue.
    EDIT: I found this program which inspects clipboard contents directly - http://www.peterbuettner.de/develop/tools/clipview/ which may also be of use.
    Sean Ellis - uses Skype chat for serious work
    Click here to read my blog post on Skype 7 and basic principles of GUI design

  • Random Row From ResultSet

    Hi, i need some help on this:
    First, my JSP will query a database table and return a resultset that contains a lot of records. Is there a way to randomly choose ONE of the record from resultset ?
    Number of records return by the resultset is dynamic (always change), so, is there a way to store all the records into array first?
    Or do you have any other suggestions ?
    Thank you !

    Better way is to create a Bean for the row returned by the Result Set. For example your result set return 2 columns i.e. ID and Name then your bean should have getter and setter methods for the columns and repeating the loop for the Result set store each returned row in the bean and then store this bean in the Collection. This is better way to work with it.

  • Retrieving the entire row from ResultSet

    Hi All,
    I am using SQL database and wants to get the data from tables as rows instead of columns. Please let me know if any of you know how to retrieve the rows from table using ResultSet.
    Thanks.

    you would need a loop like this:
    for( int i = 0; i < resultset.getMetadata().getColumnCount(); i++ )
      System.out.print( resultSet.getXXX( i ) );
    }That will print out the row

  • How can obtain a row from an attribute

    Hi, i´m doing a smart project and i need only one row, how can obtain it?
    The row i want obtain it from an attribute.
    Thanks,

    Finally i do it with this method:
         public Vector getFile(MeIterator syncBos, int fromIndex, int count, String id) {
              // We want usually all items in the MEIterator because the SmartSync API already delivered
              // the correct part of items we want to display.
              // the fromIndex and count variable are only there in case we need a single entry.          
              Vector retVec = new Vector();
              int i = 0;
              if (syncBos != null) {
                   syncBos.reset();
                   // Fill table header with Field Names of Top Row
                   while (syncBos.hasNext()) {
                        /*                    SyncBo sb = (SyncBo) syncBos.next();
                                            if (i >= fromIndex) {
                                                 Vector rowData = new Vector();
                                                 for (int col = 0; col < getColumns(); col++) {
                                                      rowData.addElement(getHeaderFieldValue(sb, tableHeaderNames[col]));
                                                 retVec.addElement(rowData);
                        Row row = (Row) syncBos.next();
                        if (i >= fromIndex) {
                             Vector rowData = new Vector();
                             if ((getHeaderFieldValue(row, tableHeaderNames[1])).equals(id)) {
                                  for (int col = 0; col < getColumns(); col++) {
                                       rowData.addElement(getHeaderFieldValue(row, tableHeaderNames[col]));
                                  retVec.addElement(rowData);                              
                        i++;
                        // return when count has been reached, when count is greater 0.
                        // if count less 0 we get all records.
                        if (count > 0) {
                             if (i >= (fromIndex + count))
                                  return retVec;
              return retVec;
    Thanks,

  • Removing Duplicate Rows from resultSet

    I have a query pulling data from 5 tables in 12 columns. I have rows where all of the data is duplicated with the exception of one date column. How would I go about deleting rows that are duplicates with the exception of this one column? I still need to pull the date from the date column with the Max(date).
    i.e.
    Bob Smith 1 2 3 4 12-Jul-2006
    Bob Smith 1 2 3 4 02-Aug-2006
    Bob Smith 1 2 3 4 21-Jan-2006
    Form this resultset I only want one row
    Thanks.

    this example might be of help.
    SQL> select * from employees;
    YEAR EM NAME       PO
    2001 02 Scott      91
    2001 02 Scott      01
    2001 02 Scott      07
    2001 03 Tom        81
    2001 03 Tom        84
    2001 03 Tom        87
    6 rows selected.
    SQL> select year, empcode, name, position,
      2         row_number() over (partition by year, empcode, name
      3                            order by year, empcode, name, position) as rn
      4    from employees;
    YEAR EM NAME       PO         RN
    2001 02 Scott      01          1
    2001 02 Scott      07          2
    2001 02 Scott      91          3
    2001 03 Tom        81          1
    2001 03 Tom        84          2
    2001 03 Tom        87          3
    6 rows selected.
    SQL> Select year, empcode, name, position
      2    From (Select year, empcode, name, position,
      3                 row_number() over (partition by year, empcode, name
      4                                    order by year, empcode, name, position) as rn
      5            From employees) emp
      6   Where rn = 1;
    YEAR EM NAME       PO
    2001 02 Scott      01
    2001 03 Tom        81
    SQL> Delete From employees
      2   Where rowid in (Select emp.rid
      3                     From (Select year, empcode, name, position,
      4                                  rowid as rid,
      5                                  row_number() over (partition by year, empcode, name
      6                                            order by year, empcode, name, position) as rn
      7                             From employees) emp
      8                    Where emp.rn > 1);
    4 rows deleted.
    SQL> select * from employees;
    YEAR EM NAME       PO
    2001 02 Scott      01
    2001 03 Tom        81
    SQL> if you can post a sample create tables and data it will help us provide you a some solutions.

  • Help :add multiple rows from Resultset to ArrayList ?

    My query returns one column and multiple rows. In Java code , I am trying to get this data in array or arraylist through ResultSet
    ex:
    item_num
    p001
    p002
    p003
    when I print, it only gets the item in the first row.
    ArrayList myArrayList = new ArrayList();
    resultset = preparedstatement.executeQuery();
    if (resultset.next())
    myArrayList.add(new String(resultset.getString("item_num")));
    Print:
    for (int j = 0 ; j < myArrayList.size() ; j++ )
    System.out.println((String)myArrayList.get(j)); --this prints only the first item.
    can someone assist ?

    changing if to while fixed it.

  • Accessing and comparing rows from resultset

    Post Author: pross
    CA Forum: Formula
    I am a newbie, and this might be a simple answer ( I hope so)
    I would like to compare rows inside my result set. For example, if I recieve information such as:
    CUSTOMER:12345 AMOUNT:100.00 CUSTOMER:12345 AMOUNT(100.00) CUSTOMER:2345 AMOUNT:75.00 CUSTOMER:4567 AMOUNT:25.00
    I want to be able match the same customer number and amounts that balance out &#91; 100.00 and (100.00)&#93;, to not show in my report.
    How can I do this?
    Thanks                    

    Post Author: pross
    CA Forum: Formula
    I am returning rows that match my criteria. Because of the way the data is stored, it shows a record that has a positive value (a charge) and a negative value for the same criteria (a payment). I want to only show records that do not have a negative value, as well as the record that shows the charge for that record. For instance I want to be able to match everything in my row as well as the amounts from those two rows sum to 0. I am not sure how to do this in a sql query or be able to filter it out in CR.

  • Output displaying last row from resultset

    I have a class called user, which has only first, last name and email. I have a method in a UserDB class that reads a database and puts the results into the user class, then stores each user object in a vector. I know there are only 3 records, and my display is only showing the last record 3 times. I can't figure out what I am doing wrong.
    UsersServlet - calls the readRecord method and creates the vector to be stored in a session
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
              MurachPool connectionPool = MurachPool.getInstance();
              Connection connection = connectionPool.getConnection();
              Vector user = UserDB.readRecord(connection);
              HttpSession session = request.getSession();
              session.setAttribute("users", user);
              RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/user11/users.jsp");
            dispatcher.forward(request, response);
         }UserDB class - read record method.
    public static synchronized  Vector readRecord(Connection connection)
              User user = new User();
              Vector vector = new Vector();
              try{
                        String sql = "SELECT * FROM User ";
                        Statement statement = connection.createStatement();
                        ResultSet rs = statement.executeQuery(sql);
                        while(rs.next())
                             user.setFirstName(rs.getString("FirstName"));
                             user.setLastName(rs.getString("LastName"));
                             user.setEmailAddress(rs.getString("EmailAddress"));
                             vector.addElement(user);
                        return vector;
              }catch(SQLException e){
                   return null;
         }The jsp display page.
    <% java.util.Vector users = (java.util.Vector)session.getAttribute("users");
       for (int i =0; i<users.size(); i++){
          business.User user = (business.User)users.get(i);
          %>
      <tr valign="top">
        <td><p><%= user.getFirstName() %></p></td>
        <td><p><%= user.getLastName() %></p></td>
        <td><p><%= user.getEmailAddress() %></p></td>
         <td><p><%= i %></p></td>
        <td><a href="/user11/ShowUserServlet?emailAddress=<%=user.getEmailAddress()%>">Update</a></td>
        <td><a href="/user11/DeleteUserServlet?emailAddress=<%=user.getEmailAddress()%>">Delete</a></td>
      </tr>
      <%}%>

    A Vector is really an array of pointers. When you add the same User object to the vector several times you are adding many pointers to the same object. In this program you want several User objects, so you need to create a new one each iteration of the loop.
    You'll also need to close the ResultSet, Statement and Connection. Preferably in a finally statement.

  • How i can display multiple row from one row

    Hi ,
    i have table called temp_probabaility and contain 2 colomns (id1 , path )the values as below ,
    ID1 Path
    3 ;2,4,6
    4 ;1;2;3;5
    5 ;1;2;3;4;5
    i need to convert the values to be like below ,
    id1 path
    3 2
    3 4
    3 6
    4 1
    4 2
    4 3
    4 5
    please any help ?
    Edited by: user11309581 on May 13, 2011 4:13 PM
    Edited by: user11309581 on May 13, 2011 4:16 PM
    Edited by: user11309581 on May 13, 2011 4:18 PM

    BluShadow wrote:
    it just needs to use the \d+ as you did.Not sure what you mean. Your code did not produce any rows for id1=6:
    SQL> with x as (select 6 as id1, ';;;' path from dual)
      2  --
      3  -- end of test data
      4  --
      5  select id1, regexp_substr(path,'\d+',1,rn) as path
      6  from   x cross join (select rownum rn
      7                       from dual
      8                       connect by rownum <= (select max(length(regexp_replace(path,'[^;]'))) from x))
      9  where regexp_substr(path,'\d+',1,rn) is not null
    10  order by 1,2
    11  /
    no rows selected
    SQL> with t as (select 6 as id1, ';;;' path from dual)
      2  -- end of on-the-fly data sample
      3  select  id1,
      4          regexp_substr(path,'\d+',1,column_value) path
      5    from  t,
      6          table(
      7                cast(
      8                     multiset(
      9                              select  level
    10                                from  dual
    11                                connect by level <= length(regexp_replace(path,'[^;]'))
    12                             )
    13                     as sys.OdciNumberList
    14                    )
    15               )
    16  /
           ID1 PAT
             6
             6
             6
    SQL> Same when path is NULL:
    SQL> with x as (select 6 as id1, '' path from dual)
      2  --
      3  -- end of test data
      4  --
      5  select id1, regexp_substr(path,'\d+',1,rn) as path
      6  from   x cross join (select rownum rn
      7                       from dual
      8                       connect by rownum <= (select max(length(regexp_replace(path,'[^;]'))) from x))
      9  where regexp_substr(path,'\d+',1,rn) is not null
    10  order by 1,2
    11  /
    no rows selected
    SQL> with t as (select 6 as id1, '' path from dual)
      2  -- end of on-the-fly data sample
      3  select  id1,
      4          regexp_substr(path,'\d+',1,column_value) path
      5    from  t,
      6          table(
      7                cast(
      8                     multiset(
      9                              select  level
    10                                from  dual
    11                                connect by level <= length(regexp_replace(path,'[^;]'))
    12                             )
    13                     as sys.OdciNumberList
    14                    )
    15               )
    16  /
           ID1 P
             6
    SQL> SY.

Maybe you are looking for

  • Can't install oracle10g on windows vista

    I downloaded oracle10g for windows vista & windows from oracle's site. But when I tried to install/setup.exe,error message that says install/setup.exe contains information about the folder.Use active/checkout instead. can anyone help me how to resolv

  • How can I publish an iBook for a client?

    I'm a designer and I have a friend that would like to publish his book for the iPad. What is the best way to go about this?

  • Slow Motion Help

    Hello, I am shooting HDV with Canon XH-A1 in 60i for slow mo shots. I bring it into JES de-interlacer to slow the footage down and now I want to convert it to 24p to bring it into a 24fps timeline in FCP. When I open the clip in Cinema Tools, it wont

  • Upgraded L to SL to ML - Now Have Problem

    I have a Mac Pro 3,1 with 6 GB RAM running 10.5.8 and iLife08. Had local Apple Retailer install additional 3TB HD with 10.6.8, iLife11 and copy all data from 10.5.8 to new HD with 10.6.8. When plugged in at home, everything worked great in SL and iLi

  • There are no templates in my newly installed LR5, Swdish version for Windows 7. How to get them?

    Dear all, I have uesed LR since LR2, most recently in a purchased upgarde licence for LR5. Having now switched to a new "Windows 7 computer of high performance I had to subscribe to LR5 and PS in the new licencing model. I have thus downloade LR5, th