如何使用Mybatis记录连接信息

时间:2016-08-16 18:42:09

标签: mybatis spring-mybatis

当我在数据库连接上出错时,我需要记录它(使用数据库名称和尝试连接数据库的用户名,不需要记录密码),我在我的应用程序上使用Sprig-Mybatis

任何想法如何做到这一点?

最好的问候

1 个答案:

答案 0 :(得分:0)

没有其他特殊方法可以做,因为java中的简单try / catch会让你获得预期。 例如,我调用mybatis映射器方法的简单程序:

    try{
    List result = mapper.myBatisMapperMethod();//this is responsible to set up 
                                              //a connection and run a query
    }

假设上述调用由于身份验证无效而失败,请在下面说明我的密码错误连接 异常我通常会进入mybatis:

Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Login failed for user 'applicationUsername'.)
        Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Login failed for user 'applicationUsername'.)
            at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1225)
            at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
            at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
            at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
            ... 65 more
        Caused by: 
    com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'applicationUsername'.

我所做的是上面有一个简单的捕获尝试你可以捕获一个sql异常,但在这里我只使用异常

 catch(Exception e){
        //Suppose you are using Log4j You can simply
        logger.error("This is my error log message"+e.getMessage());
        //The above will log any kind of exception including the authentication fail or you 
        can specifically log a particular kind of exception.Java wont log failed password it just logs the user who tried unless you explicitly want to log it.
    }