Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any better, more idiomatic way to convert SQL ResultSet to a Scala List or other collection type?

Tags:

scala

jdbc

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()

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

like image 842
user6502167 Avatar asked Jan 19 '18 05:01

user6502167


People also ask

How do I convert a ResultSet to a list?

You need to use ResultSet#getString to fetch the name . Now, each time you fetch one record, get the name field and add it to your list. Now, since you haven't given enough information about your DTO , so that part you need to find out, how to add this ArrayList to your DTO .

Which method is used to move to the last record in ResultSet?

You can move the cursor of the ResultSet object to the last row from the current position, using the last() method of the ResultSet interface. This method returns a boolean value specifying whether the cursor has been moved to the last row successfully.

What are methods associated with the ResultSet?

The ResultSet interface provides getter methods ( getBoolean , getLong , and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1.


2 Answers

Why don't you try this:

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

Taken from this answer here

like image 134
SCouto Avatar answered Oct 13 '22 14:10

SCouto


I have a similar problem and my solution is:

Iterator.from(0).takeWhile(_ => rs.next()).map(_ => rs.getString(1)).toList

Hope that will help.

like image 45
Michal Przysucha Avatar answered Oct 13 '22 13:10

Michal Przysucha