priya
priya

Reputation: 4367

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).

Upvotes: 2

Views: 28859

Answers (2)

Koziołek
Koziołek

Reputation: 2874

// 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[].

Upvotes: -1

Nishant
Nishant

Reputation: 55866

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!

Upvotes: 11

Related Questions