Dynamically load the JDBC driver

前端 未结 2 616
无人及你
无人及你 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:55

    You cannot do it this way, because DriverManager doesn't allow you to use drivers that the calling code doesn't have access to (i.e. drivers loaded by different classloader):

    When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.

    As far as I know the only possible workaround is to instantiate Driver manually instead of using DriverManager (assuming that it has a no-arg constructor):

    Driver driver = Class.forName(drivername, true, loader).newInstance();
    Connection connect = driver.connect(url, props);
    

    Though I'm not sure that it's a correct approach.

提交回复
热议问题