Dynamically load the JDBC driver

前端 未结 2 554
无人及你
无人及你 2021-02-13 17:24

I\'m trying to load the JDBC driver dynamically with this kind of code:

        try{
        URL[] url={new URL(\"file:libs/mysql-connector-java-5.1.21.jar\")};
         


        
2条回答
  •  太阳男子
    2021-02-13 17:35

    that's a known issue with DriverManager and classloaders, see:

    http://www.kfu.com/~nsayer/Java/dyn-jdbc.html

    Driver definition (basically a delegate):

    class DriverShim implements Driver {
        private Driver driver;
        DriverShim(Driver d) { this.driver = d; }
        public boolean acceptsURL(String u) throws SQLException {
            return this.driver.acceptsURL(u);
        }
        public Connection connect(String u, Properties p) throws SQLException {
            return this.driver.connect(u, p);
        }
        // and so on....
    

    Use example:

    URL u = new URL("jar:file:/path/to/pgjdbc2.jar!/");
    String classname = "org.postgresql.Driver";
    URLClassLoader ucl = new URLClassLoader(new URL[] { u });
    Driver d = (Driver)Class.forName(classname, true, ucl).newInstance();
    DriverManager.registerDriver(new DriverShim(d));
    DriverManager.getConnection("jdbc:postgresql://host/db", "user", "pw");
    

提交回复
热议问题