Java Reference
In-Depth Information
The following listing shows the complete
Geocoder
class, with its method
fillInLatLng
that takes a
Stadium
as an argument and fills in the latitude and lon-
gitude values.
Listing 2.3.
Geocoder.groovy
, which uses the Google geocoder to compute lat and lng
class Geocoder {
def base = 'http://maps.googleapis.com/maps/api/geocode/xml?'
def fillInLatLng(Stadium stadium) {
def url = base + [sensor:false,
address: [stadium.name, stadium.city, stadium.state].
collect
{
URLEncoder.encode(it,'UTF-8')
}.
join
(',')
].
collect
{k,v -> "$k=$v"}.
join
('&')
def response = new XmlSlurper().parse(url)
stadium.latitude =
response.result[0].geometry.location.lat.
toDouble
()
stadium.longitude =
response.result[0].geometry.location.lng.
toDouble
()
return stadium
}
}
The groovy.sql.Sql class
Returning to the original problem, I want to store the stadium information in a database.
I'm now going to take advantage of a very useful class in the Groovy library,
groovy.sql.Sql
. This class connects to a database and allows you to execute SQL
against it. To begin the process, here's how the
Sql
class is instantiated:
Sql db = Sql.
newInstance
(
'jdbc:mysql://localhost:3306/baseball',
'...username...',
'...password...',
'com.mysql.jdbc.Driver'
)
The
Sql
class has a static
newInstance
method, whose arguments are the JDBC URL,
the username and password, and the driver class. The result is a connection to the database.
Next, I drop the stadium table if it already exists:
db.execute "drop table if exists stadium;"