How to get database instance in grails?

I am new to Grails and I have doubts. Suppose I have mine Datasource.groovyconfigured for a database mysql. Everything works fine and the grails app works.

In the controller, if I want to add / change the database that I installed in Datasource.groovy, how can I do this?

Again I need to do something like this in each controller:

def db = Sql.newInstance(
                    'jdbc:mysql://*****',
                    'root',
                    '',
                    'com.mysql.jdbc.Driver'
                )

to get a db instance that I point to a Datasource.groovyfile?

Are there any recommendations for this?

+5
source share
1 answer

You should do this (I would recommend that this be done in the service, not in the controller, as this will make your controllers cleaner and the code easier to follow)

import groovy.sql.Sql 

class DataSourceAccessingService {
  def datasource

  def runSomeQuery( String sql ) {
    def sql = new Sql( datasource )
    ...
  }
}
+5

All Articles