Java (JDBC) :查询结果迭代的备选方案 [ while(resultSet.next()) ]

Java (JDBC) : Alternatives for iteration of query results [ while(resultSet.next()) ]

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

while(resultSet.next()){

}


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

了解 ORM - Object/Relational 映射:

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

我推荐 Spring JPA 或 Hibernate。

您可以使用 getString(int columnIndex) or getString(String columnLabel) 方法在不循环的情况下检索结果,例如:

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

或索引:

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

你可以做一个 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.