Java(JDBC):查询结果迭代的替代方法[while(resultSet.next())]

时间:2015-04-28 09:27:23

标签: java sql jdbc

我正在寻找任何替代方案:

while(resultSet.next()){

}
  • 我试图避免不需要循环的循环;

  • 我正在寻找最简单的方法来返回一个结果;

欢迎任何简短的注释和答案。

3 个答案:

答案 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)

阅读ORM - 对象/关系映射:

http://en.wikipedia.org/wiki/Object-relational_mapping

我推荐Spring JPA或Hibernate。

答案 2 :(得分:0)

您可以使用getString(int columnIndex) getString(String columnLabel) 方法无需循环检索结果,例如:

resultSet.next();
String name = resultSet.getString("name");

或索引:

 resultSet.next();
String name = resultSet.getString(1);