9.2 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 ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access