How to use a JDBC driver from an arbitrary location

后端 未结 2 707
盖世英雄少女心
盖世英雄少女心 2020-12-03 05:35

I need to test a JDBC connection to a database. The java code to do that should be as simple as:

DriverManager.getConnection(\"jdbc connection URL\", \"usern         


        
相关标签:
2条回答
  • 2020-12-03 05:44

    From the article Pick your JDBC driver at runtime; I am just going to post the code here for reference.

    The idea is to trick the driver manager into thinking that the driver was loaded from the system classloader. To do this we use this class:

    public class DelegatingDriver implements Driver
    {
        private final Driver driver;
    
        public DelegatingDriver(Driver driver)
        {
            if (driver == null)
            {
                throw new IllegalArgumentException("Driver must not be null.");
            }
            this.driver = driver;
        }
    
        public Connection connect(String url, Properties info) throws SQLException
        {
           return driver.connect(url, info);
        }
    
        public boolean acceptsURL(String url) throws SQLException
        {
           return driver.acceptsURL(url);
        }
    
        public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException
        {
            return driver.getPropertyInfo(url, info);
        }
    
        public int getMajorVersion()
        {
            return driver.getMajorVersion();
        }
    
        public int getMinorVersion()
        {
            return driver.getMinorVersion();
        }
    
        public boolean jdbcCompliant()
        { 
            return driver.jdbcCompliant();
        }
    }
    

    This way the driver you register is of type DelegatingDriver which is loaded with the system classloader. You now just have to load the driver you really want to use using whatever classloader you want. For example:

    URLClassLoader classLoader = new URLClassLoader(new URL[]{"path to my jdbc driver jar"}, this.getClass().getClassLoader());
    Driver driver = (Driver) Class.forName("org.postgresql.Driver", true, classLoader).newInstance();
    DriverManager.registerDriver(new DelegatingDriver(driver)); // register using the Delegating Driver
    
    DriverManager.getDriver("jdbc:postgresql://host/db"); // checks that the driver is found
    
    0 讨论(0)
  • 2020-12-03 06:05

    The problem is DriverManager performs "tasks using the immediate caller's class loader instance". See Guideline 6-3 of Secure Coding Guidelines for the Java Programming Language, version 2.0. The system class loader is in no way special in this case.

    Just for kicks, I wrote a blog entry on this subject a while back. My solution, though more complicated then Nick Sayer's solution, is more complete and even works from untrusted code. Also note URLClassLoader.newInstance is preferred over new URLClassLoader.

    0 讨论(0)
提交回复
热议问题