Connecting to a Database

To connect to a database, simply create an instance of groovy.sql.Sql by calling the static method newInstance. One version of this method accepts the database URL, user ID, password, and database-driver name as parameters. If we already have a java.sql.Connection instance or a java.sql.DataSource, then instead of using newInstance, we can use one of the constructors for Sql that accepts those.

We can obtain the information about the connection by calling the Sql instance’s getConnection method (the connection property). When we’re finished, we can close the connection by calling the close method. Here is an example of connecting to the database we created for this chapter:

WorkingWithDatabases/Weather.groovy
 
def ...

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.