Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

adding multiple rows to a list

 
dilip satyaraghava
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21296
32
Eclipse IDE Firefox Browser MySQL Database
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 197
Java Oracle Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic