Monday, December 18, 2006

Groovy from SQL and templates

Groovy is a real fun! Get some data from database and put it to XML - must be quick-n-dirty :)
Let the table be:
-- Apache Derby ij script
connect 'jdbc:derby:../../myderby;create=true;user=test;password=test';
create table test(
name varchar(20),
age integer,
gender char(1)
insert into test values ('John Doe', 55, 'M');
insert into test values ('Diana Smith', 34, 'F');
insert into test values ('Foo Bar', 21, 'M');
... and the template.txt:
.. and now, Groovy rocks! :)
import groovy.sql.Sql
import groovy.text.Template
import groovy.text.SimpleTemplateEngine

class SQL2XML{
static void main(args) {
def file = new File("template.txt")
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(file)
def sql = Sql.newInstance("jdbc:derby:myderby",
"test", "test",
sql.eachRow("SELECT * FROM TEST") {
def binding = ["name":"${}",
def result = template.make(binding)
println result

It seems to me that the dynamic features might be useful for adding customizations to the end-user application.

1 comment:

Yuri Schimke said...

When I was at Aqris, I got a prototype groovy visitor working with RefactorIT. The idea being you could share refactoring scripts etc. Sort of at the level of System.out to Log4J migration scripts etc.

It worked pretty well in the end. But wasn't ever release quality.

Disqus for Code Impossible