你好,我正在尝试通过类加载器加载我的 jdbc 驱动程序
我在这里是代码,但如果可能的话为什么我会得到这个错误而不是给我一些例子
我不知道要设置什么类路径变量
我正在制作一个数据库应用程序,这个应用程序需要一次又一次地连接数据库,我想把这个应用程序给我的 friend ,但我的 friend 不知道类路径,他就像普通用户一样,
我的应用程序可以连接 4 种类型的数据库 MS-Access、MySQL、Oracle、SQLlite... 在用户系统中,我必须设置 5 个类路径变量并提供 5 个 jar 文件
如果我给这个应用程序 100 个人而不是他们设置类路径变量
我可以在我的应用程序中包含 jar 文件,但是我如何动态设置类路径.... 请提供一些例子...
package classload;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ClassLoad {
static Connection con;
public static void main(String[] args) {
File jar = new File("C:\\query\\Driver.jar").getAbsoluteFile();
if(jar.exists()){
System.out.print("File exits");
}
URL urls[] = null;
try {
urls = new URL[] {
jar.toURI().toURL()
};
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClassLoader cl = new URLClassLoader(urls);
try {
Class.forName("com.mysql.jdbc.Driver", true, cl);
con=DriverManager.getConnection("jdbc:mysql://localhost", "root", "anil");
Statement stm=con.createStatement();
ResultSet result=stm.executeQuery("select *from actor");
while(result.next()){
System.out.print(result.getInt(1)+" "+result.getString(2)+" "+result.getString(3));
System.out.println("");
}
} catch (SQLException e) {
System.out.println(e);
}catch(ClassNotFoundException e){
System.out.println(e);
}
}
}
异常(exception)是
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost
最佳答案
只需使用 One-Jar将应用程序和所有依赖项打包到单个 fat jar 中。你的解决方案不好。您的 friend 必须使用与您相同的文件夹结构才能使其正常工作。
关于java - jdbc动态类加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25123373/