将SQL ResultSet转换为Scala列表或其他集合类型的更好,更惯用的方法吗? [英] Any better, more idiomatic way to convert SQL ResultSet to a Scala List or other collection type?

查看:227
本文介绍了将SQL ResultSet转换为Scala列表或其他集合类型的更好,更惯用的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下朴素代码将ResultSet转换为Scala List:

I'm using the following naive code to convert a ResultSet to a Scala List:

val rs = pstmt.executeQuery()
var nids = List[String]()
while (rs.next()) {
  nids = nids :+ rs.getString(1)
}
rs.close()

有没有一种更好的方法,对于Scala来说更惯用了,不需要使用可变对象?

Is there a better approach, something more idiomatic to Scala, that doesn't require using a mutable object?

推荐答案

您为什么不尝试以下操作:

Why don't you try this:

new Iterator[String] {
  def hasNext = resultSet.next()
  def next() = resultSet.getString(1)
}.toStream

从此答案中摘录此处

这篇关于将SQL ResultSet转换为Scala列表或其他集合类型的更好,更惯用的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆