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

I have a context.xml file in the format below

<Context shallowOutput="true" path="/"> <WatchedResource>WEB-INF/web.xml</WatchedResource> <Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource" factory="org.apache.commons.dbcp.BasicDataSourceFactory" driverClassName="oracle.jdbc.driver.OracleDriver" username="OMITTED" password="OMITTED" url="OMITTED" maxActive="20" maxIdle="10" maxWait="-1"/> 

From this contex.xml I need to get the name of my driver.

Every time i try

DataSource ds = (DataSource)context.lookup("java:/jdbc/myDataSource")

and try to get the driver class name from the connection using

ds.getConnection().getMetatData().getDriverName()

It returns only Oracle JDBC Driver instead of the class name oracle.jdbc.driver.OracleDriver

How to get class name from context.

+6
source share
4 answers

I think the best you can hope for is:

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

Metadata must return the URL for this connection, and the URL prefix must be registered using the DriverManager (unique).

+6
source

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

For JDBC connectivity, it looks like this:

 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 a simple procedure that shows the name of the connection class:

 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 the Oracle connection that I used in the test I received:

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

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

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

complete the task.

0
source

Using Tomcat (7) 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 enable 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> 
0
source

All Articles