Feeds

Groovy way to MySQL

Get your Groove on

Securing Web Applications Made Simple and Scalable

As with Java, Groovy makes use of JDBC to interact with the database. So we'll start off with some simple code to connect to and read from this database. Enter the following into a file called MySQL.groovy:

import groovy.sql.Sql
def sql = Sql.newInstance("jdbc:mysql://192.168.16.175:3306/pers", "pan","regdev", "com.mysql.jdbc.Driver")
sql.eachRow("select * from users") {println "User name ${it.user_name}"}

The first thing to note is the import statement and the creation of the Sql object. The argument to the newInstance method broadly encapsulates the information needed to create a standard Java JDBC connection: database URL, user name, password, and JDBC driver class name.

Once we've got an Sql object we can use it to interact with the database using standard SQL syntax. In this example we are simply performing a basic select query to grab all of the data in the user's table. So far, not very different from Java, the Groovy code is less verbose for sure, but not so different to what we're used to. It's what follows that shows us a first taste of Groovy at work.

The eachRow method iterates through the rows returned by the select query, and this is combined with the closure code: {println "User name ${it.user_name}"}

Closures are blocks of code that are treated as objects and can be passed around, stored, or executed. In this case we are creating a block of code that is passed to the eachRow method, which then executes the function by binding the value of each row of data to the "it" variable. In this way we can access all of the column names in the returned rows directly. If we save this code as MySQL.groovy we can then execute it from the command line by typing:

groovy MySQL.groovy

which will return:

User name tom
User name dick
User name harry
User name george

This combination of SQL, easy iteration and the use of closures means it's possible to write extremely powerful but succinct scripts to process data from MySQL and other databases. The eachRow method isn't the only way we can access the data using the Sql class. As an alternative we can grab the rows and put them into a List as follows:

List u=sql.rows('SELECT * FROM users')
u.each {println it.user_id}

Again, we have an iteration and a closure providing fast access to processing the data.

However, the Sql class also provides a means to perform a wide variety of SQL operations, including INSERT, DELETE, UPDATE and various DDL activities.

We can use Groovy's triple quoted strings to encode SQL queries which we execute directly. For example:

sql.execute '''
  INSERT INTO users (user_name, email, user_id) 
  VALUES ('fred','fred@fred.com',99);'''
sql.execute '''
  DELETE FROM users 
  WHERE user_id>20
  '''

So far we've been using the Sql class to provide access to the database. In the next part of this tutorial we'll be looking at a different mechanism and at some practical examples of using Groovy scripting with MySQL to perform some common DBA activities. ®

Bridging the IT gap between rising business demands and ageing tools

More from The Register

next story
NO MORE ALL CAPS and other pleasures of Visual Studio 14
Unpicking a packed preview that breaks down ASP.NET
DARPA-derived secure microkernel goes open source tomorrow
Hacker-repelling, drone-protecting code will soon be yours to tweak as you see fit
Cheer up, Nokia fans. It can start making mobes again in 18 months
The real winner of the Nokia sale is *drumroll* ... Nokia
Put down that Oracle database patch: It could cost $23,000 per CPU
On-by-default INMEMORY tech a boon for developers ... as long as they can afford it
Google shows off new Chrome OS look
Athena springs full-grown from Chromium project's head
Apple: We'll unleash OS X Yosemite beta on the MASSES on 24 July
Starting today, regular fanbois will be guinea pigs, it tells Reg
HIDDEN packet sniffer spy tech in MILLIONS of iPhones, iPads – expert
Don't panic though – Apple's backdoor is not wide open to all, guru tells us
prev story

Whitepapers

Designing a Defense for Mobile Applications
Learn about the various considerations for defending mobile applications - from the application architecture itself to the myriad testing technologies.
Implementing global e-invoicing with guaranteed legal certainty
Explaining the role local tax compliance plays in successful supply chain management and e-business and how leading global brands are addressing this.
Top 8 considerations to enable and simplify mobility
In this whitepaper learn how to successfully add mobile capabilities simply and cost effectively.
Seven Steps to Software Security
Seven practical steps you can begin to take today to secure your applications and prevent the damages a successful cyber-attack can cause.
Boost IT visibility and business value
How building a great service catalog relieves pressure points and demonstrates the value of IT service management.