Modifying data in an SQL database
The logical step after querying a database (see the Querying an SQL database recipe) is writing data to it. This recipe shows how a few lines of Groovy and very little boilerplate is needed to do the job of modifying data in a database table.
Getting ready
This recipe also uses the same table structure and the way to start a database server defined in the Creating a database table recipe.
How to do it...
As usual, create a new Groovy script named modifyDb.groovy
. As for the previous recipes, in this case we also need to import the DBUtil
class.
Add the following code to the newly created script:
import static DBUtil.* import groovy.sql.Sql def server = startServer() createSchema()
The next logical step is to define the initial data to write to the database. Add the following code to the script, a variable containing a list of Maps with the data to persist:
def cookbooks = [ [ id: 1, title: '30-minute-meals', author: 'Jamie Oliver', year: 2010], ...