I am working on a Grails application where I must access several datasources. The datasources are defined in the default database (ie. they are stored there and I must make
You can add multiple data sources in a single application, and access them in the services.
Firstly you need to add basic data sources in the resources.groovy.
first import BasicDataSource
import org.apache.commons.dbcp.BasicDataSource;
Then
switch (grails.util.GrailsUtil.environment) {
case "development":
firstDataSource( BasicDataSource ) {
driverClassName = "net.sourceforge.jtds.jdbc.Driver"
url = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName="
username = "sa"
password = "root"
String SqlServerInstance = "SQLEXPRESS";
url = url + ";" + SqlServerInstance;
}
break
case "test":
firstDataSource( BasicDataSource ) {
driverClassName = "net.sourceforge.jtds.jdbc.Driver"
url = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName="
username = "sa"
password = "root"
String SqlServerInstance = "SQLEXPRESS";
url = url + ";" + SqlServerInstance; }
break;
}
In the same way you can add more data sources, above code will give you one more datasource to access other than the default one. I used switch to configure same data source for the different environments, same way more can be added.
and in the service it can be accessed in the services as:
BasicDataSource firstDataSource;
Connection con = firstDataSource.getConnection();
and then connection object can be used.
I think it should help