Reputation:
I'm searching for any alternative for this :
while(resultSet.next()){
}
I am trying to avoid loop where they are not needed ;
I am searching for the simpliest way to return one single result ;
Any brief annotation and answer is welcome.
Upvotes: 2
Views: 2313
Reputation: 65793
You could make a ResultSetIterator
:
class ResultSetIterator implements Iterator<ResultSet> {
private final ResultSet r;
private ResultSet next = null;
public ResultSetIterator(ResultSet r) {
this.r = r;
}
@Override
public boolean hasNext() {
if (next == null) {
try {
if (r.next()) {
next = r;
}
} catch (SQLException ex) {
// NB: Log this error.
}
}
return next != null;
}
@Override
public ResultSet next() {
ResultSet n = next;
next = null;
return n;
}
}
Then - with careful avoidance of repeating the iterator - perhaps using a SingleUseIterable
:
/**
* Makes sure the iterator is never used again - even though it is wrapped in an Iterable.
*
* @param <T>
*/
public static class SingleUseIterable<T> implements Iterable<T> {
protected boolean used = false;
protected final Iterator<T> it;
public SingleUseIterable(Iterator<T> it) {
this.it = it;
}
public SingleUseIterable(Iterable<T> it) {
this(it.iterator());
}
@Override
public Iterator<T> iterator() {
if (used) {
throw new IllegalStateException("SingleUseIterable already invoked");
}
used = true;
// Only let them have it once.
return it;
}
}
/**
* Adapts an {@link Iterator} to an {@link Iterable} for use in enhanced for loops.
*
* If {@link Iterable#iterator()} is invoked more than once, an {@link IllegalStateException} is thrown.
*
* @param <T>
* @param i
* @return
*/
public static <T> Iterable<T> in(final Iterator<T> i) {
return new SingleUseIterable<>(i);
}
You can now do:
public void test() {
ResultSet resultSet = null;
// ...
try {
for (ResultSet r : in(new ResultSetIterator(resultSet))) {
// We're there.
}
} finally {
if (resultSet != null) {
resultSet.close();
}
}
}
Which is much more elegant. Remember to close
your ResultSet
.
Upvotes: 2
Reputation: 32145
You can retrieve a result without looping using the getString(int columnIndex) or getString(String columnLabel) methods, for example:
resultSet.next();
String name = resultSet.getString("name");
Or with index:
resultSet.next();
String name = resultSet.getString(1);
Upvotes: 0
Reputation: 340
Read about ORM - Object/Relational Mapping:
http://en.wikipedia.org/wiki/Object-relational_mapping
I recommend Spring JPA or Hibernate.
Upvotes: 1