Store Each Row In A Resultset As An Object In An Array
Essentially my problem is that I am returning a resultset from a jdbc query and i want to store each row as an object in an array. when i try to loop through the resultset- it only
Solution 1:
Try combining the loops:
ResultSetrs= st.executeQuery(query);
rs.last();
intnumberOfRows= rs.getRow();
Check checkArray [] = newCheck [numberOfRows];
rs.beforeFirst();
while (numberOfRows > 0 && rs.next()) {
Checkc=newCheck();
c.setAmount(rs.getBigDecimal("AMOUNT"));
c.setCheckNumber(rs.getString("CHECKNUMBER"));
...
checkArray[i]= c;
numberOfRows--;
}
Solution 2:
ResultSethas getArray function so you could use like that.
checkArray[i]= rs.getArray(int columnIndex);
Solution 3:
Unless your ResultSet is an instance of CachedRowSet, it won't know how many rows there are and will return a zero from .getRow()
The main problem with your code is that you are reusing the same Check instance over and over, meaning all elements of your array are the same Check object. You ned to create a new instance for every row
Better load all rows into a List and use while (resultSet.next()) to control to loop.
If you absolutely need an array, convert the List to an array at the end with List.toArray()
An abbreviated version of the code is:
List<Check> list = new ArrayList<Check>();
while (rs.next()) {
Check c = new Check();
// set fields of c
list.add(c);
}
Check[] checkArray = list.toArray();
Post a Comment for "Store Each Row In A Resultset As An Object In An Array"