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
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
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With