【问题标题】:jdbc dynamic class loadingjdbc动态类加载
【发布时间】: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


【解决方案1】:

只需使用One-Jar 将应用程序和所有依赖项打包到单个 fat jar 中。你的解决方案不好。您的朋友必须使用与您相同的文件夹结构才能正常工作。

【讨论】:

    【解决方案2】:

    出现此错误可能是因为所需的 jar 文件 mysql-connector 尚未包含在您的项目中。尝试包含 jar 文件,如 here 所示。并尝试使用此代码加载驱动程序类:

    Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jlcstudents","root","password");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 2016-08-18
      • 2012-04-23
      相关资源
      最近更新 更多