自定义ClassLoader加载mysql驱动

背景:最近在研究自定义类加载器ClassLoader加载自定义目录的jar时,当加载mysql驱动时总是报ClassNotFoundException。

原因:当DriverManager加载驱动时只承认当前系统的加载器加载的jar,自定义的显然不承认。

3、解决办法:

自定义myDriver实现Driver接口,并实现接口方法,其包含成员变量Driver即可。

public class MyDriver implements Driver {
    public MyDriver(Driver driver) {
        this.driver = driver;
    }

    private Driver driver;

    @Override
    public Connection connect(String url, Properties info) throws SQLException {
        return this.driver.connect(url, info);
    }

    @Override
    public boolean acceptsURL(String url) throws SQLException {
        return this.driver.acceptsURL(url);
    }

    @Override
    public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
        return this.driver.getPropertyInfo(url, info);
    }

    @Override
    public int getMajorVersion() {
        return this.driver.getMajorVersion();
    }

    @Override
    public int getMinorVersion() {
        return this.driver.getMinorVersion();
    }

    @Override
    public boolean jdbcCompliant() {
        return this.driver.jdbcCompliant();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
Driver driver = null;// (Driver)app.newInstance();

        try {
             driver = (Driver) Class.forName("com.mysql.jdbc.Driver",true,paveClassLoader)
                        .newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

DriverManager.registerDriver( new MyDriver(driver) );
Connection conn = DriverManager.getConnection(url, user, password);

以上即全部过程。

小插曲:在利用conn查询时遇到java.sql.SQLException: Before start of result set异常,这个是因为没有调用rs.next()方法导致,需要每次调用rs.getxxx()前都要使cursorPos向前移动1步。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章