Database Select
We can use the Sql object to conveniently iterate through data in a table. Simply call the eachRow method, provide it with a SQL query to execute, and give it a closure to process each row of data, thusly:
WorkingWithDatabases/Weather.groovy | |
| println "City Temperature" |
| sql.eachRow('SELECT * from weather') { |
| printf "%-20s%s\n", it.city, it[1] |
| } |
The data fetched using the previous code is as follows:
| City Temperature |
| Austin 48 |
| Baton Rouge 57 |
| Jackson 50 |
| Montgomery 53 |
| Phoenix 67 |
| Sacramento 66 |
| Santa Fe 27 |
| Tallahassee 59 |
We asked eachRow to execute the SQL query on the weather table to process all its rows. We then iterated (as the name each indicates) over each row. There’s more grooviness here—we can use the ...
Get Programming Groovy 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.