像处理 Scala 流一样处理 SQL ResultSet [英] Treating an SQL ResultSet like a Scala Stream
问题描述
当我查询一个数据库并收到一个(只进,只读)ResultSet 时,ResultSet 就像一个数据库行列表.
When I query a database and receive a (forward-only, read-only) ResultSet back, the ResultSet acts like a list of database rows.
我试图找到某种方法来像对待 Scala Stream
一样处理这个 ResultSet.这将允许诸如 filter
、map
等操作,同时不会消耗大量 RAM.
I am trying to find some way to treat this ResultSet like a Scala Stream
. This will allow such operations as filter
, map
, etc., while not consuming large amounts of RAM.
我实现了一个尾递归方法来提取单个项目,但这要求所有项目同时在内存中,如果 ResultSet 非常大,就会出现问题:
I implemented a tail-recursive method to extract the individual items, but this requires that all items be in memory at the same time, a problem if the ResultSet is very large:
// 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)
}
}
推荐答案
我没有测试过,但为什么它不起作用?
I didn't test it, but why wouldn't it work?
new Iterator[String] {
def hasNext = resultSet.next()
def next() = resultSet.getString(1)
}.toStream
这篇关于像处理 Scala 流一样处理 SQL ResultSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!