我正在运行一个select命令,它返回100万行迭代ResultSet.以下代码需要5分钟才能执行.
是否有更快的迭代结果集的方法?
conn = getDbConnection();
Statement createStatement = conn.createStatement();
ResultSet rs = createStatement.executeQuery("Select * from myTable");
while (rs.next())
{
//do nothing
}
Run Code Online (Sandbox Code Playgroud)
java中是否有一种方法可以在查看结果集中的所有记录时提高效率.
谢谢
Pra*_*ate 12
您可以使用setFetchSize(rows)优化获取大小,从DB中一次获取指定的行数.
conn = getDbConnection();
Statement createStatement = conn.createStatement();
createStatement.setFetchSize(1000);
ResultSet rs = createStatement.executeQuery(“Select * from myTable”);
while (rs.next())
{
//do nothing
}
Run Code Online (Sandbox Code Playgroud)
请注意,fetchSize只是一个提示DB,它可能会忽略该值.只有测试才能揭示它是否是最佳的.
此外,在您的情况下,更改ScrollableStatement的属性可能更好,因为您可能不会立即处理所有记录.选择哪个可滚动选项取决于您是否要在迭代时查看其他更改.
//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);
Run Code Online (Sandbox Code Playgroud)
要么
//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);
Run Code Online (Sandbox Code Playgroud)
要么
//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);
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅JDBC API指南