如何在java中使用数据源对象获取数据库配置 [英] How to get database configurations using data source object in java

查看:657
本文介绍了如何在java中使用数据源对象获取数据库配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我陷入了与java中的数据源对象相关的问题。
我在数据源对象(org.apache.tomcat.jdbc.pool.DataSource)中设置了数据源连接参数。我想在调用getConnection方法之前从数据源对象中获取这些参数,如果它捕获异常,则在catch内部记录有意义的调试信息。

I'm stuck in a issue related to data source objects in java. I have set data source connection parameters in data source object(org.apache.tomcat.jdbc.pool.DataSource). I wants to get those parameters from data source object before i call getConnection method log meaningful debug info inside catch if it catches exception.

以下是我试过的代码。我可以从元数据中获取所有连接参数,如下所示[例如: - connection.getMetaData()。getURL()],但我想捕获异常并将日志url,密码,用户名作为日志,如果getConnection()抛出异常。因此,我需要在尝试创建数据库连接之前从数据源对象获取这些信息。

Following is the code so far i have tried. I can get all the connection parameters from metadata as follows[ex:- connection.getMetaData().getURL()], but i wants to catch exception and log url,password,username as a log if getConnection() throws exception. Therefore, i need to get those information from data source object before it tries to creates db connection.

try {
        // try to get the lookup name. If error empty string will be returned
        jndiLookupName = connectionProperties.getProperty(RDBMSConstants.PROP_JNDI_LOOKUP_NAME);
        datasource = InitialContext.doLookup(jndiLookupName);

        connection = datasource.getConnection(); // WHEN THIS THROWS EXCEPTION...

        logger.info(connection.getMetaData().getURL()); // these won't work since exception already thrown.
        logger.info(connection.getMetaData().getUserName());
        logger.info(connection.getMetaData().getDriverName());
        logger.info(connection.getMetaData().getDriverVersion());

        isConnected = true; // if no errors
        logger.info("JDBC connection established with jndi config " + jndiLookupName);

    } catch (SQLException e) {

        //...I WANT ALL CONNECTION PARAMETERS (URL,PASSWORD,USERNAME) HERE

        throw new SQLException("Connecting to database failed with jndi lookup", e);
    }

当我远程调试时,我得到数据源对象如下..

When i remote debug i get data source object as follows..

org.apache.tomcat.jdbc.pool.DataSource@d47feb3{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=com.mysql.jdbc.Driver; maxActive=100; maxIdle=8; minIdle=0; initialSize=0; maxWait=30000; testOnBorrow=false; testOnReturn=false; timeBetweenEvictionRunsMillis=5000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=60000; testWhileIdle=false; testOnConnect=false; password=********; url=jdbc:mysql://localhost/wso2_mb_1; username=a; validationQuery=null; validationQueryTimeout=-1; validatorClassName=null; validationInterval=30000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=false; removeAbandonedTimeout=60; logAbandoned=false; connectionProperties=null; initSQL=null; jdbcInterceptors=ConnectionState;StatementFinalizer;org.wso2.carbon.ndatasource.rdbms.ConnectionRollbackOnReturnInterceptor;; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; suspectTimeout=0; alternateUsernameAllowed=false; commitOnReturn=false; rollbackOnReturn=false; useDisposableConnectionFacade=true; logValidationErrors=false; propagateInterruptState=false; ignoreExceptionOnPreLoad=false; }

我可以看到所有的url,用户名和密码参数都在那里,但我无法得到那些。有没有办法从数据源对象中获取这些值。

I can see all the url, username and password parameters are there but i can not get those. Is there a way to get these values from data source object.

推荐答案

转换为 DataSource - tomcat池化数据源提供对用户名 url 等的访问权限。有关详细信息,请 DataSource ):

Cast to the concrete implementation of the DataSource - the tomcat pooled datasource provides access to username, url etc. (see DataSource for details):

if (dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource) {
    org.apache.tomcat.jdbc.pool.DataSource tcDataSource = (org.apache.tomcat.jdbc.pool.DataSource)dataSource;
    logger.info(tcDataSource.getUrl());
    logger.info(tcDataSource.getUsername());
    ...
}

这篇关于如何在java中使用数据源对象获取数据库配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆