问题描述
我在做一个查询来获取大量的ID(整数)。而是通过ResultSet迭代数百万次,将所有内容复制一个接一个到一个ArrayList的,是有一些方法来只检索一切,一个ArrayList
据我了解,ResultSet的应该是迭代,因为底层的实现可能会缓存的东西,但在我的情况下,我只需要所有的ID,立竿见影。我知道我可以设置FETCHSIZE大量,但后来我还有一个接一个检索的标识。
澄清:我想这样做的原因是性能。分析显示我这样做ResultSet.next(),ResultSet.getInt()和ArrayList.add()数百万次需要相当长一段时间。我估计,该数据库(我使用的是H2,它是用Java编写的)可能有数组或列表的地方在内存中,所以我在寻找一种方式把它复制到我,而不是直接通过ResultSet接口迭代
使用Apache 库您可以轻松地返回ResultSet作为地图列表。
公开名单查询(查询字符串){
列表结果= NULL;
尝试{
QueryRunner QRUN =新QueryRunner();
结果=(列表)qrun.query(连接,查询,新MapListHandler());
}赶上(例外前){
ex.printStackTrace();
}
返回结果;
}
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?
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.
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.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!