Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 从数据源检索数据库名称_Mysql_Grails_Datasource - Fatal编程技术网

Mysql 从数据源检索数据库名称

Mysql 从数据源检索数据库名称,mysql,grails,datasource,Mysql,Grails,Datasource,在config.groovy文件中,我定义了dataSource.url='jdbc:mysql://localhost/mydbname?autoReconnect=true&characterEncoding=utf8" 是否可以从控制器中检索“mydbname”?我已经注入了dataSource,它提供了一个 org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy但是从那里,我不知道如何获得数据库名。应该在不进

在config.groovy文件中,我定义了dataSource.url='jdbc:mysql://localhost/mydbname?autoReconnect=true&characterEncoding=utf8"

是否可以从控制器中检索“mydbname”?我已经注入了dataSource,它提供了一个 org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy但是从那里,我不知道如何获得数据库名。应该在不进行任何字符串解析的情况下检索DB名称,因为应用程序使用的配置在不同的环境中可能会发生很大的变化,因此理想情况下,我要寻找一种类似.getDatasourceName()的方法

我试过这个:
flash.message=“DB name${dataSource.getConnection().getClientInfo()}”
但是返回的消息是:
DB name[:]

我认为最好的方法是检索URL,然后解析出数据库名称。您可以这样做:

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, '?')
  }
}
无论任何数据源URL参数如何,它都应返回数据库名称,例如,它将适用于以下所有情况:

  • jdbc:mysql://localhost/mydbname?autoReconnect=true&characterEncoding=utf8
  • jdbc:mysql://localhost/mydbname?autoReconnect=true
  • jdbc:mysql://localhost/mydbname
最常规的方式:

def dataSource
private String getDatabaseName(){
    def url = dataSource.targetDataSource.targetDataSource.poolProperties.url
    return url.split('/').toList().last().tokenize('?')[0]      
}

它有两种工作方式,有url参数和没有url参数。

您可以运行SQL语句来获得:我当前使用的是:final sqlQuery=sessionFactory.currentSession.createSQLQuery(“选择数据库()”)params.db_name=sqlQuery.uniqueResult(),但我也会测试您的答案。@Giannis我不认为
选择数据库()
是可移植的,但如果您总是使用MySQL,我想这并不重要