Question

I'm working on some software that sometimes needs to connect to an oracle 8.1.7 database, and sometimes to an oracle 10g database in order to perform some queries.

When connecting to the 8.1.7 database I need to use the ojdbc14.jar drivers, and the ojdbc6.jar drivers for the 10g database.

It seems that the automatic driver selection isn't smart enough to select the correct driver when both of these drivers are in the classpath, is there any way that I can specify which one is preferred in my code?

I'm not currently using any connection pool or similar abstractions, but it wouldn't be a problem to introduce something like that if needed.

Was it helpful?

Solution

If you are not using dbcp then you can do it like this

class Test 
        static Driver driver5;
        static Driver driver6;

        static void init() throws Exception {
            ClassLoader cl5 = new URLClassLoader(new URL[] { new URL("file:lib/ojdbc15.jar") });
            driver5 = (Driver) cl5.loadClass("oracle.jdbc.driver.OracleDriver").newInstance();
            ClassLoader cl6 = new URLClassLoader(new URL[] { new URL("file:lib/ojdbc6.jar") });
            driver6 = (Driver) cl6.loadClass("oracle.jdbc.driver.OracleDriver").newInstance();
        }

        public static void main(String[] args) throws Exception {
            Properties props = new Properties();
            props.put("user", "user");
            props.put("password", "pwd");
            String url = "jdbc:oracle:thin:@host:1529:sid";
            Connection conn5 = driver5.connect(url, props);
            Connection conn6 = driver6.connect(url, props);
        }

Note that ojdbc15.jar and ojdbc6.jar should not be on java classpath, they should be invisible for application classloader

OTHER TIPS

You cannot decide that which driver will use at runtime using connection pool, but using connection pool(which have defination in xml format) you need not to compile your code again and again after changing the driver.

But for runtime driver selection implementation, you can create a your own a SQL helper class in which all SQL configuration and SQL related operation will be perform. In that create a method called openConnection(String driver, String username, String password), here you can decide which driver shold we use at runtime.

Your can create a Driver Factory Class which abstract which driver version to use

from your runtime supply the input as which type of driver you want and Factory should return that purticular type

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top