Inserting and Updating

We can use the DataSet object to add data, not just filter data. The add method accepts a map of data to create a row, as shown in the following code:

WorkingWithDatabases/Weather.groovy
 
println ​"Number of cities : "​ + sql.rows(​'SELECT * from weather'​).size()
 
dataSet.add(city: ​'Denver'​, temperature: 19)
 
println ​"Number of cities : "​ + sql.rows(​'SELECT * from weather'​).size()

The following output shows the effect of executing that code:

 
Number of cities : 8
 
Number of cities : 9

More traditionally, however, we can insert data using the Sql class’s execute or executeInsert method, as shown here:

WorkingWithDatabases/Weather.groovy
 
temperature = 50
 
sql.executeInsert(​"""INSERT INTO weather (city, temperature) ...

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.