File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases 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 and Relational Databases
Bookmark "adding multiple rows to a list" Watch "adding multiple rows to a list" New topic

adding multiple rows to a list

dilip satyaraghava

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

Joined: Oct 14, 2005
Posts: 19973

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: 195

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

Murad Iqbaal

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

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 method, and keep adding the object returned in a Collection till returns false i.e. no more records left.

Take this code as a sample:

Hope this makes sense and helps.
I agree. Here's the link:
subject: adding multiple rows to a list
It's not a secret anymore!