我正在寻找任何替代方案:
while(resultSet.next()){
}
我试图避免不需要循环的循环;
我正在寻找最简单的方法来返回一个结果;
欢迎任何简短的注释和答案。
答案 0 :(得分:2)
您可以制作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;
}
}
然后 - 小心避免重复迭代器 - 也许使用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);
}
您现在可以:
public void test() {
ResultSet resultSet = null;
// ...
try {
for (ResultSet r : in(new ResultSetIterator(resultSet))) {
// We're there.
}
} finally {
if (resultSet != null) {
resultSet.close();
}
}
}
哪个更优雅。请记住close
ResultSet
。
答案 1 :(得分:1)
答案 2 :(得分:0)
您可以使用getString(int columnIndex)或 getString(String columnLabel) 方法无需循环检索结果,例如:
resultSet.next();
String name = resultSet.getString("name");
或索引:
resultSet.next();
String name = resultSet.getString(1);