动态加载JDBC驱动代码示例,仅供参考
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.*;
import java.util.Properties;
public class test {
public static void main(String[] args) {
test1();
//test2();
}
public static Connection test1(){
Connection connection = null;
try {
File driverFile = new File("C:\\Users\\wanjian.cao\\gsjdbc4.jar");
URLClassLoader classLoader = classLoader = new URLClassLoader(new URL[]{driverFile.toURI().toURL()});
// 动态加载驱动类
Driver d = (Driver)Class.forName("org.postgresql.Driver", true, classLoader).newInstance();
DriverImpl driver = new DriverImpl(d);
DriverManager.registerDriver(driver);
connection = DriverManager.getConnection("jdbc:postgresql://ip:5432/postgres","xxx","xxx");
System.out.println("获取连接成功" + connection.toString());
} catch (Exception e) {
e.printStackTrace();
}
return connection;
// TODO 根据需要做 DriverManager.deregisterDriver(driver) 操作
}
public static Connection test2() {
Connection connection = null;
try {
String JDBC_DRIVER_PATH = "C:/Users/wanjian.cao/gsjdbc4.jar";
// 创建一个新的类加载器,用于加载JDBC驱动
URLClassLoader classLoader = new URLClassLoader(new URL[]{new File(JDBC_DRIVER_PATH).toURI().toURL()});
// 使用新的类加载器加载驱动类
Class<?> driverClass = Class.forName("org.postgresql.Driver", true, classLoader);
// 创建驱动实例
Driver driver = (Driver) driverClass.getDeclaredConstructor().newInstance();
// 创建连接
connection = driver.connect("jdbc:postgresql://ip:5432/postgres", new Properties() {{
setProperty("user", "xxx");
setProperty("password", "xxx");
}});
System.out.println("获取连接成功" + connection.toString());
}catch (Exception e){
e.printStackTrace();
}
return connection;
}
static class DriverImpl implements Driver {
private Driver driver;
DriverImpl(Driver d) {
this.driver = d;
}
@Override
public boolean acceptsURL(String u) throws SQLException {
return this.driver.acceptsURL(u);
}
@Override
public Connection connect(String u, Properties p) throws SQLException {
return this.driver.connect(u, p);
}
@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 java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
return this.driver.getParentLogger();
}
}
}