For my application I need dynamic database connections at runtime. I know, there are ways to create multiple datasources but they are not that dynamically I think. Scenario:
A user can enter database credentials and connect to a remote database to import single rows and tables to an other database. For this purpose I need to connect to the remote database dynamically.
I've tried to do that in a service like they've said in If I use groovy sql class in grails, does it use the grails connection pooling?
Note: GORM is dispensable in this case, I can use plain SQL instead.
Any ideas? Thank you..
Edit: Grails 2.3.4
As long as you have the JDBC drivers for all the datasources on your classpath, you can create an instance of
groovy.sql.Sql
that will connect to whatever database you like, e.g.You can do this sort of thing to register DataSource beans at runtime:
Given a Grails Service:
Then, you should be able to call the service to register a new datasource:
Get a Groovy Sql object for it:
And remove the bean when done
Fingers crossed... I've yanked that code from a project of mine and changed/not-tested it ;-)
Update
The runtime-datasources plugin has been created which uses the approach outlined in this post to allow datasources to be added/removed at runtime.