栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从任意位置使用JDBC驱动程序

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从任意位置使用JDBC驱动程序

从文章中选择运行时的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 DriverDriverManager.getDriver("jdbc:postgresql://host/db"); // checks that the driver is found


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/573775.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号