当我查询数据库并接收到(只进只读)ResultSet时,ResultSet的行为与数据库行列表相似。像Scala流一样处理SQL ResultSet
我想找到一些方法来对待这个ResultSet,比如Scala Stream
。这将允许诸如filter
,map
等的操作,而不消耗大量的RAM。
我实现了一个尾递归的方法来提取单个项目,但是这要求所有项目在记忆的同时,一个问题,如果ResultSet是非常大的:
// Iterate through the result set and gather all of the String values into a list
// then return that list
@tailrec
def loop(resultSet: ResultSet,
accumulator: List[String] = List()): List[String] = {
if (!resultSet.next) accumulator.reverse
else {
val value = resultSet.getString(1)
loop(resultSet, value +: accumulator)
}
}
可以使用Iterable而不是Stream来执行您想要的操作吗? – 2012-03-09 17:19:36
另外一个流将保留内存中的值,所以当你到达列表的末尾时,你不会真正保存内存。 – 2013-07-30 13:16:53
我认为如果没有jdbc标志/选项使得jdbc自己对结果进行流式处理,那么您的内存中仍然有一个完整的数据副本,由您的jdbc api构建。 – matanster 2016-03-08 20:57:41