Giannis Giannis - 4 months ago 33
MySQL Question

Retrieve Database name from dataSource

Inside my config.groovy file I define dataSource.url='jdbc:mysql://localhost/mydbname?autoReconnect=true&characterEncoding=utf8'

Is it possible to retrieve 'mydbname' from within a controller? I have injected dataSource, which is giving a
org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy but from there, I cant figure how to get the DB name. The DB name should be retrieved without any String parsing, as the configurations used for the app can change a lot between environments, so ideally I am looking for a method like .getDatasourceName()

I have tried this:

flash.message = "DB name ${dataSource.getConnection().getClientInfo()}"
but the message returned is this:
DB name [:]

Answer

I think the best you can do is retrieve the URL, then parse out the database name. You can do this like so:

import org.apache.commons.lang.StringUtils

class MyController {

  DataSource dataSource

  String getDatabaseName() {
    def url = dataSource.targetDataSource.targetDataSource.poolProperties.url

    url = StringUtils.substringAfterLast(url, '/')
    return StringUtils.substringBefore(url, '?')
  }
}

This should return the database name regardless of any datasource URL params, e.g. it will work for all of the following:

  • jdbc:mysql://localhost/mydbname?autoReconnect=true&characterEncoding=utf8
  • jdbc:mysql://localhost/mydbname?autoReconnect=true
  • jdbc:mysql://localhost/mydbname