2008-11-14 19 views
17

我需要测试到数据库的JDBC连接。 Java代码做的,应该是这么简单:如何从任意位置使用JDBC驱动程序

DriverManager.getConnection("jdbc connection URL", "username", "password"); 

驱动程序管理器将查找相应的对于给定的连接URL的驱动程序。不过,我需要能够在运行时加载JDBC驱动程序(jar)。 I.e在运行上述代码片段的Java应用程序的类路径中没有JDBC驱动程序。

这样我就可以使用此代码,例如加载驱动程序:

URLClassLoader classLoader = new URLClassLoader(new URL[]{"jar URL"}, this.getClass().getClassLoader()); 
Driver driver = (Driver) Class.forName("jdbc driver class name", true, classLoader).newInstance(); 

但随后的驱动程序管理器仍然不会把它捡起来,因为我不能告诉它要使用的类加载器。我尝试设置当前线程的上下文类加载器,但它仍然无法工作。

任何人有任何想法实现这一目标的最佳途径?

+0

为什么你在类路径中没有驱动程序有充分的理由吗? – 2008-11-14 00:16:10

回答

17

来自文章Pick your JDBC driver at runtime;我只是在这里发布代码以供参考。

这个想法是欺骗司机经理认为驱动程序是从系统类加载器加载的。要做到这一点,我们使用这个类:

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(); 
    } 
} 

这样你注册驱动程序是加载系统类加载器DelegatingDriver类型。你现在只需要使用你想要的任何类加载器来加载你真正想使用的驱动程序。例如:

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