Assigning a specific entry in the ResultSet to a variable

I want to get a set of records from a database, do rs.next (), and then assign the result of that to a variable to navigate to the method that will use that record, in the same way I am not assigning it to a variable and passing it to the method. or a way to do it? I am using JAVA (1.5)


Thanks for all the answers

I don't want to pass the entire resultSet to the method, only the current row, but as I understand it, this cannot be done

+1


source to share


4 answers


Do you want to assign the result to rs.next () variable?

I'm afraid you can't do this. You can have a link from that rs and handle it in a different way (just like you wouldn't assign it to var)

When you pass rs as an argument to a method, which is exactly what you are already doing.



while( rs.next() ) { 
    list.add( createFrom( rs ) );
}

...

public Object createFrom( ResultSet rs ) {  // Here rs is a copy of the reference in the while above. 
}

      

Did I understand your question correctly?

0


source


No, this is not supported out of the box, but maybe the following idea can help you:

ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
  Map<String,Object> row = new HashMap<String,Object>();
  for (int i = 1; i <= meta.getColumnCount(); ++i) {
    row.put(meta.getColumnName(i), rs.getObject(i));
  }
  processRow(row);
}

      



The problem is that you need to map the values ​​from row

-map to processRow()

, and that won't work for all type / driver combinations (BLOB, ...).

+1


source


I think I understand you now. :)

No, it cannot be done like this. ResultSet

changes its internal state on every call to ResultSet.next()

, so keeping a reference to it won't get you. You need to extract the data you want into some custom object and save it.

CustomData cd = new CustomData();
cd.setString1(rs.getString(1));
cd.setInt1(rs.getInt(2));
...

      

Then you can save the variable cd

and continue processing ResultSet

.

0


source


I often find the List> data structure very useful when working with result sets.

-1


source







All Articles