How to get driver class name (not driver name) from jdbc connection

时间秒杀一切 提交于 2019-12-03 12:23:11

I think the best you can hope for is:

DriverManager.getDriver(ds.getConnection().getMetaData().getURL()).getClass();

The metadata should return the URL for this connection and the URL prefix should be registered with the DriverManager (uniquely).

For any object you can use object.getClass().getName()

For JDBC connection it looks like:

String db_class = DriverManager.getConnection(db_url, usr, passwd).getClass().getName();

For my PostgreSQL driver it returns:

org.postgresql.jdbc4.Jdbc4Connection

In your code this should work:

ds.getConnection().getClass().getName()

And simple procedure that shows class name of connection:

public static void show_connection_info(Connection conn)
    {
    System.out.println("Connection: " + conn);
    System.out.println("Connection class: " + conn.getClass());
    System.out.println("Connection class name: " + conn.getClass().getName());
    }

For Oracle connection I used in test I got:

Connection: oracle.jdbc.driver.T4CConnection@1e1c66a
Connection class: class oracle.jdbc.driver.T4CConnection
Connection class name: oracle.jdbc.driver.T4CConnection

I use a "try" algorithm based on reflection. OracleDataSource contains the driver in a "driver" attribute, and there may be lots of DataSource that does the same. So the following :

Field field = dataSource.getClass().getDeclaredField("driver");
field.setAccessible(true);
return field.get(dataSource).getClass().getName();

do the job.

Using Tomcat (7) this works:

if(source instanceof org.apache.tomcat.dbcp.dbcp.BasicDataSource){
    logger.info("Driver className: "+((org.apache.tomcat.dbcp.dbcp.BasicDataSource)source).getDriverClassName());
}

You will also need to include the dbcp library at build time:

<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-dbcp -->
<dependency><!-- to check driver name effectively running -->
        <scope>provided</scope>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-dbcp</artifactId>
        <version>7.0.47</version>
</dependency>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!