Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: How to access to the values already set in DataSource

I have a groovy application which is using an Oracle DB as DataSource.

In DataSource.groovy I've set:

dataSource {
pooled = true
driverClassName = "oracle.jdbc.driver.OracleDriver"
username = "scott"
password = "tiger
//loggingSql = true
}

For some performance reasons at some points I am accesing the DB using sql in the following way:

def sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:XE", "scott", "tiger", "oracle.jdbc.driver.OracleDriver") 

That is, username and password are hardwired twice in the application. My question is if it possible to address in my application to the attributes username and password already set in the DataSource.groovy.

Thanks in advance,

Luis

like image 935
Luixv Avatar asked Sep 21 '09 16:09

Luixv


2 Answers

The solution is to add some imports

import javax.sql.DataSource
import groovy.sql.Sql
import org.codehaus.groovy.grails.commons.ConfigurationHolder

and the following code:

def _url      = ConfigurationHolder.config.dataSource.url
def _username = ConfigurationHolder.config.dataSource.username
def _password = ConfigurationHolder.config.dataSource.password
def _driver   = ConfigurationHolder.config.dataSource.driverClassName
def sql = Sql.newInstance(_url, _username, _password, _driver)

def query = "<your SQL query>"
sql.eachRow(query){
    println "ID: " + it.id // Whatever you need
}
like image 73
Luixv Avatar answered Nov 11 '22 21:11

Luixv


You may create Sql class by datasource, for example

def sql = new Sql(myDataSource)

where myDataSource - object of class DataSource (you can get your DS declared in DataSource.groovy)

like image 1
Alexey Sviridov Avatar answered Nov 11 '22 21:11

Alexey Sviridov