aspose file tools*
The moose likes JDBC and the fly likes adding multiple rows to a list Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "adding multiple rows to a list" Watch "adding multiple rows to a list" New topic
Author

adding multiple rows to a list

dilip satyaraghava
Greenhorn

Joined: Nov 22, 2011
Posts: 8
i have retrived multiple rows from database and now i want to add each row to a collection.. i dont know the number of rows i retrieved .. so how do i add each row to the list
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18907
    
    8

You add them one at a time. Each time you read a row from the database, you add it to the list. It isn't necessary to know in advance how many rows you are going to add.

Now if you had chosen an array, you would have had to know in advance. That's why choosing a list instead of an array, as you did, is a good idea.
Prabhakar Reddy Bokka
Ranch Hand

Joined: Jul 26, 2005
Posts: 193

Create your own bean with the attributes present in the row, and set all the results to the bean, and finally add the bean to a list. This iteration is for every record in the result set.

see below link for examples. hope that helps.

Data access using JDBC


SCJP 5, SCWCD 5
Murad Iqbaal
Greenhorn

Joined: Feb 02, 2012
Posts: 9
1. Create your own bean as Prabhakhar said
2. Create a generic collection for your bean for example ArrayList<YourBean>
3. use the addAll(Collection list) method to pass the retrieved http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)


Also, if you mean you don't know the number of items you retrieved, then its simple. Get an iterator and use its hasNext method to determine if there is another object after the current pointer. If there is, then use the next() method in a loop to retrieve the object and keep adding in a collection. Also, if you dont want to use iterator, use the resultset.next method, and keep adding the object returned in a Collection till rs.next() returns false i.e. no more records left.

Take this code as a sample:



Hope this makes sense and helps.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: adding multiple rows to a list