concept eachRow in category groovy

appears as: eachRow
Groovy in Action, Second Edition

This is an excerpt from Manning's book Groovy in Action, Second Edition.

This eachRow method takes a string as an argument that corresponds to a SQL query. The cool news is, with type check extensions, you can even type-check the literal string for being a syntactically correct SQL statement!

The methods eachRow and query use a closure for processing the result. query calls the given closure once and passes the full java.sql.ResultSet into it; eachRow calls the closure for each row of the result, thus relieving the programmer from the usual iteration work.

You can achieve this by using eachRow and a simple selection statement. The row that’s passed into the closure is an interesting object. You can use the column names as if they were property names of that object:

println ' Athlete Info '.center(25,'-')
def fmt = new java.text.SimpleDateFormat('dd. MMM yyyy (E)',
                                         Locale.US)
db.eachRow('SELECT * FROM Athlete'){ athlete ->
    println athlete.firstname + ' ' + athlete.lastname
    println 'born on '+ fmt.format(athlete.dateOfBirth)
    println '-' * 25
}