SQL with Groovy

Posted on by By Somen Sarkar, in Databases, ETL, Javascript | 0

SQL with Groovy

Groovy provides a handy way to handle jdbc when compared to java. Playing with database becomes very easy with groovy. To use SQL scripting with groovy we have to use the  groovy.sql.Sql package.

Make data easy with Helical Insight.
Helical Insight is the world’s best open source business intelligence tool.

Lets Start 30 Days Free Trail

import groovy.sql.Sql

sql = Sql.newInstance( 'jdbc:jtds:sqlserver://serveripName/databaseName-CLASS;domain=yourdomainname', 'dbusername', 'dbpassword', 'driverclass' )

sql.eachRow( 'select * from tableName' ) {
println "$it.slno -- ${it.userName} --"
}

The Sql.newInstance method helps to create database connection. It takes the parameters like database username, database password, driver class and jdbc url.
The sql.eachRow method is used to fire SQL query and iterate the resultset aswell.

Groovy has provision to handle performance with transaction based query. We can use the batch withBatch method to handle the performance issue.

sql.eachRow("SELECT * FROM employee WHERE filter_criteria ", { employee ->
// Process employee and add update statement to batch
def updateStmts = processEmployee(employee)
stmt.addBatch(updateStmts)
})
})

 

For the sake of integrity we can define the withTransaction block along withBatch

sql.withTransaction {
def result = sql.withBatch({ ... })
...
}

 

When we know that the result set is only one row.

row = sql.firstRow('select columnA, columnB from tableName')
firstRow method helps us to retrive the first row.
def ans = sql.firstRow("select * from PERSON where location_id < $location")
println ans.firstname

groovy insert statement with closure

sql.execute("insert into employee (employeName, empAddress) values (${employeeName}, ${empAddress})")

sql.close().

This method closes the sql connection, and takes care of the connection.

These were only few methods. To know more we can explore the groovy.sql package.

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments