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?
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 .
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.
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.
Why don't you try this:
new Iterator[String] {
def hasNext = resultSet.next()
def next() = resultSet.getString(1)
}.toStream
Taken from this answer here
I have a similar problem and my solution is:
Iterator.from(0).takeWhile(_ => rs.next()).map(_ => rs.getString(1)).toList
Hope that will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With