Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treating an SQL ResultSet like a Scala Stream

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 treat this ResultSet like a Scala Stream. This will allow such operations as filter, map, etc., while not consuming large amounts of RAM.

I implemented a tail-recursive method to extract the individual items, but this requires that all items be in memory at the same time, a problem if the ResultSet is very large:

// Iterate through the result set and gather all of the String values into a list // then return that list @tailrec def loop(resultSet: ResultSet,          accumulator: List[String] = List()): List[String] = {   if (!resultSet.next) accumulator.reverse   else {     val value = resultSet.getString(1)     loop(resultSet, value +: accumulator)   } } 
like image 463
Ralph Avatar asked Mar 09 '12 15:03

Ralph


People also ask

What is ResultSet getString ()?

getString(String columnLabel) Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. Time. getTime(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a java.

What is ResultSet Concur_updatable?

It is a constant of the ResultSet class representing the concurrency mode for a ResultSet object that may be updated. In general, you will pass this as a value to the createStatement() method.

What is a ResultSet in SQL?

An SQL result set is a set of rows from a database, as well as metadata about the query such as the column names, and the types and sizes of each column. Depending on the database system, the number of rows in the result set may or may not be known.

What is ResultSet Concur_read_only?

The field ResultSet. CONCUR_UPDATABLE creates a ResultSet object that can be updated while CONCUR_READ_ONLY creates a ResultSet that cannot be updated but only it can be read. The problem that you cannot see any changes that you made in the database table is because you are using read only type ResultSet.


1 Answers

I didn't test it, but why wouldn't it work?

new Iterator[String] {   def hasNext = resultSet.next()   def next() = resultSet.getString(1) }.toStream 
like image 187
elbowich Avatar answered Nov 13 '22 05:11

elbowich