我正在运行一个 select 命令,该命令返回 1,000,000 行,迭代 ResultSet。下面的代码需要 5 分钟才能执行。
有没有更快的方法来迭代 ResultSet?
conn = getDbConnection();
Statement createStatement = conn.createStatement();
ResultSet rs = createStatement.executeQuery("Select * from myTable");
while (rs.next())
{
//do nothing
}
java中有没有一种方法可以在检查结果集中的所有记录时提高效率。
Thanks
您可以使用setFetchSize(rows)优化获取大小,一次从数据库中获取指定数量的行。
conn = getDbConnection();
Statement createStatement = conn.createStatement();
createStatement.setFetchSize(1000);
ResultSet rs = createStatement.executeQuery(“Select * from myTable”);
while (rs.next())
{
//do nothing
}
请注意, fetchSize 只是一个提示DB
它可能会忽略该值。只有测试才能揭示其是否最佳。
另外,就你的情况来说,改变可能会更好Scrollable
声明的属性,因为您可能无法一次处理所有记录。选择哪个可滚动选项取决于您是否希望在迭代时看到其他人的更改。
//TYPE_FORWARD_ONLY
// The constant indicating the type for a ResultSet object
// whose cursor may move only forward.
conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
Or
//TYPE_SCROLL_INSENSITIVE
// The constant indicating the type for a ResultSet object that is
// scrollable but generally not sensitive to changes made by others.
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Or
//TYPE_SCROLL_SENSITIVE
// The constant indicating the type for a ResultSet object that is
// scrollable and generally sensitive to changes made by others.
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
See JDBC API 指南欲了解更多详情
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)