背景:最近在研究自定義類加載器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步。