繁体   English   中英

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

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

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

while(resultSet.next()){

}

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

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


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

你可以创建一个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

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

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

我推荐Spring JPA或Hibernate。

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

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

或者使用索引:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM