2008-11-14 21 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