Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get database instance in grails?

I'm novice in Grails and I have a doubt. Lets say I have my Datasource.groovy configured to mysql database. Everything works fine and my grails app is running.

In the controller, if I want to add/modify the database that I have set in DataSource.groovy how I can do that?

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

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

in order to get the db instance that I point to DataSource.groovy file?

Are there any best practices to do so?

like image 547
batman Avatar asked Jul 06 '12 06:07

batman


1 Answers

You should be able to do this (I would recommend this is done in a Service rather than a Controller, as it will make your controllers cleaner and you code easier to follow)

import groovy.sql.Sql 

class DataSourceAccessingService {
  def datasource

  def runSomeQuery( String sql ) {
    def sql = new Sql( datasource )
    ...
  }
}
like image 155
tim_yates Avatar answered Sep 21 '22 17:09

tim_yates