【发布时间】:2014-09-27 04:53:30
【问题描述】:
你好我正在尝试通过类加载器加载我的 jdbc 潜水员
我是代码,但如果可能的话为什么我会得到这个错误而不是给我一些例子
我不设置什么类路径变量
我正在制作一个数据库应用程序,这个应用程序需要一次又一次地连接数据库,我想把这个应用程序给我的朋友,但我的朋友不知道类路径,他就像普通用户一样,
我的应用程序可以连接 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);
}
}
}
例外是
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost
【问题讨论】:
-
因为你在单独的类加载器中加载jdbc驱动,所以DriverManager看不到。替换当前类加载器:Thread.getCurrentThread.setClassLoader(cl);在 DriverManager.getConnection 之前。
标签: java mysql jakarta-ee jdbc