Treating an SQL ResultSet like a Scala Stream

前端 未结 10 2237
天涯浪人
天涯浪人 2020-12-02 10:11

When I query a database and receive a (forward-only, read-only) ResultSet back, the ResultSet acts like a list of database rows.

I am trying to find some way to trea

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 10:21

    Utility function for @elbowich's answer:

    def results[T](resultSet: ResultSet)(f: ResultSet => T) = {
      new Iterator[T] {
        def hasNext = resultSet.next()
        def next() = f(resultSet)
      }
    }
    

    Allows you to use type inference. E.g.:

    stmt.execute("SELECT mystr, myint FROM mytable")
    
    // Example 1:
    val it = results(stmt.resultSet) {
      case rs => rs.getString(1) -> 100 * rs.getInt(2)
    }
    val m = it.toMap // Map[String, Int]
    
    // Example 2:
    val it = results(stmt.resultSet)(_.getString(1))
    

提交回复
热议问题