Wrapping result sets in a stream

The JDBC ResultSet object plays very badly with Scala collections. The only real way of doing anything useful with it is to loop through it directly with a while loop. For instance, to get a list of the names of physicists in our database, we could write the following code:

// WARNING: poor Scala code
import Implicits._ // import implicit conversions

SqlUtils.usingConnection("test") { connection =>
  connection.withQuery("SELECT * FROM physicists") { resultSet =>
    var names = List.empty[String]
    while(resultSet.next) {
      val name = resultSet.getString("name")
      names = name :: names
    }
    names
  }
}
//=> List[String] = List(Paul Dirac, Albert Einstein, Marie Curie, Richard Feynman, Isaac Newton)

The ResultSet interface feels ...

Get Scala for Data Science now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.