Java URLClassLoader类来动态加载数据库驱动jar
使用Idea等开发工具可以很方便的自动加载驱动,但在生产环境就没有这么便捷的条件了。为了便于问题排查,于是就有了这种类似demo的小工具
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.*;
import java.util.Properties;
public class DynamicMySQLConnectionWithoutConfigFile {
public static void main(String[] args) {
String jdbcJarPath = "/Users/xxxx/Downloads/mysql-connector-j-8.0.32.jar"; // 替换为 MySQL 驱动 .jar 路径
// 直接提供数据库连接信息
String dbUrl = "jdbc:mysql://192.168.1.19:3306/db"; // 数据库地址
try {
// 动态加载 MySQL 驱动 .jar
File f = new File(jdbcJarPath);
try (URLClassLoader classLoader = new URLClassLoader(new URL[]{f.toURI().toURL()}, System.class.getClassLoader())) {
// 动态加载驱动类
Class<?> driverClass = classLoader.loadClass("com.mysql.cj.jdbc.Driver");
Driver sqlDriverInstance = ( Driver ) driverClass.newInstance();
// 连接数据库
System.out.println("正在连接数据库...");
Properties userDbCredentials = new Properties();
userDbCredentials.put( "user", "root" );
userDbCredentials.put( "password", "xxxxx" );
try (Connection connection = sqlDriverInstance.connect( dbUrl, userDbCredentials )) {
System.out.println("数据库连接成功!");
// 测试查询
String query = "SELECT VERSION() AS version";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query)) {
if (resultSet.next()) {
System.out.println("MySQL 版本: " + resultSet.getString("version"));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}