来自文章在运行时选择您的 JDBC 驱动程序;我只是在这里发布代码以供参考。
这个想法是诱使驱动程序管理器认为驱动程序是从系统类加载器加载的。为此,我们使用这个类:
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