How to convert ResultSet into Object[] and retrieve the data
I have a List<object[]> 开发者_开发百科records=null;
I am retrieving some data and storing it in to the ResultSet
.
Now, How do I convert the ResultSet
into this Object[]
and return the records(retrieved values).
For whatever weird reasons you need this. Here is how:
List<object[]> records=new ArrayList<object[]>();
while(resultSet.next()){
int cols = resultSet.getMetaData().getColumnCount();
Object[] arr = new Object[cols];
for(int i=0; i<cols; i++){
arr[i] = resultSet.getObject(i+1);
}
records.add(arr);
}
My 2 cents:
Ideally, you will have an proper object that maps Table columns to Java object fields. Instead of using an array of objects, you will set the properties to the POJO or Value Object (VO) and return the list of object. That is much simpler and makes more sense. You may want to revisit your design if you have to live on list of Object array!
// better add performance
List<object[]> records=new LinkedList<object[]>();
// call only once
int cols = resultSet.getMetaData().getColumnCount();
while(resultSet.next()){
Object[] arr = new Object[cols];
for(int i=0; i<cols; i++){
arr[i] = resultSet.getObject(i+1);
}
records.add(arr);
}
At last you can call toArray method from Collections class to get array of Object[].
精彩评论