Treating an SQL ResultSet like a Scala Stream

前端 未结 10 2241
天涯浪人
天涯浪人 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:36

    i needed something similar. Building on elbowich's very cool answer, I wrapped it a bit, and instead of the string, I return the result (so you can get any column)

    def resultSetItr(resultSet: ResultSet): Stream[ResultSet] = {
        new Iterator[ResultSet] {
          def hasNext = resultSet.next()
          def next() = resultSet
        }.toStream
      }
    

    I needed to access table metadata, but this will work for table rows (could do a stmt.executeQuery(sql) instead of md.getColumns):

     val md = connection.getMetaData()
     val columnItr = resultSetItr( md.getColumns(null, null, "MyTable", null))
          val columns = columnItr.map(col => {
            val columnType = col.getString("TYPE_NAME")
            val columnName = col.getString("COLUMN_NAME")
            val columnSize = col.getString("COLUMN_SIZE")
            new Column(columnName, columnType, columnSize.toInt, false)
          })
    

提交回复
热议问题