Reputation: 182
I have added multiple jars(ojdbc6 for oracle and jtds-1.2.jar for sqlserver ) to my classpath. When I test connection using following code :
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
if(conn==null){
System.out.println("false");
}
else{
System.out.println("true");
}
Scenario 1: If I give JDBC_DRIVER as sqlserver URL (net.sourceforge.jtds.jdbc.Driver) and DB_URL,USER,PASS for my oracle instance then also it will create connection for me but logically it is wrong.
Scenario 2: If I give some other(not oracle.jdbc.driver.OracleDriver ) valid class in ojdbc6.jar and valid DB_URL,USER,PASS then also it will create connection .
But I always want to check valid JDBC_DRIVER which corresponds to the given DB_URL,USER,PASS
I have also tried registerDriver and deregisterDriver API available in driverManager. What are the pros and cons of using it.
Upvotes: 1
Views: 2487
Reputation: 362
To check valid driver name try these lines below.
conn = DriverManager.getConnection(this.dbUrl, this.dbUser, this.dbPassword);
DatabaseMetaData dbMetaData = conn.getMetaData();
this.databaseProperties.add("Driver Name: " + dbMetaData.getDriverName());
Upvotes: 0
Reputation: 8616
Explanation for - Scenario 1/Scenario 2
From oracle documentation
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
So even you comment out Class.forName(JDBC_DRIVER);
you will get the same result as ojdbc6 is in your classpath and in DriverManager.getConnection(...);
method you are passing oracle database related information.So DriverManager
always will return the connection instance for oracle daabase only.
Explanation for- want to check valid JDBC_DRIVER which corresponds to the given DB_URL,USER,PASS
For this you can use getDriver(String url) method of DriverManager class.
getDriver(String url)
Attempts to locate a driver that understands the given URL.
Upvotes: 1