问题描述
我正在执行查询以检索大量 ID(整数).不是通过 ResultSet 迭代数百万次并将所有内容一一复制到 ArrayList 中,有没有什么方法可以简单地将所有内容检索为 ArrayList?
I'm doing a query to retrieve a large amount of IDs (integers). Instead of iterating millions of times through the ResultSet and copying everything one-by-one to an ArrayList, is there some way to simply retrieve everything as an ArrayList?
我知道 ResultSet 应该被迭代,因为底层实现可能正在缓存内容,但在我的情况下,我只需要立即获得所有 ID.我知道我可以将 FetchSize 设置为一个很大的数字,但是我仍然需要一个一个地检索 ID.
I understand that ResultSet is supposed to be iterated because the underlying implementation may be caching stuff, but in my situation I just need all the IDs straight away. I know I can set the FetchSize to a large number, but then I still have to retrieve the IDs one-by-one.
澄清:我想这样做的原因是性能.分析显示,执行 ResultSet.next()、ResultSet.getInt() 和 ArrayList.add() 数百万次需要相当长的时间.我认为数据库(我使用的是用 Java 编写的 H2)可能在内存中的某处有数组或列表,所以我正在寻找一种方法将它直接复制给我,而不是通过 ResultSet 迭代接口.
Clarification: the reason I want to do this is performance. Profiling shows me that doing ResultSet.next(), ResultSet.getInt() and ArrayList.add() millions of times takes quite some time. I figure that the database (I'm using H2, which is written in Java) probably has the array or list somewhere in memory, so I'm looking for a way to have it copied to me directly instead of through the ResultSet iterating interface.
推荐答案
使用 Apache DbUtils 库您可以轻松地将 ResultSet 作为地图列表返回.
Using the Apache DbUtils library you can easily return a ResultSet as a List of Maps.
public List query(String query) {
List result = null;
try {
QueryRunner qrun = new QueryRunner();
result = (List) qrun.query(connection, query, new MapListHandler());
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
这篇关于如何将 JDBC ResultSet 作为 ArrayList 检索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!