加载并连接到mysql jdbc驱动程序运行时

时间:2012-05-28 07:31:16

标签: java mysql runtime

我目前正在处理需要加载mysql驱动程序运行时并使用java连接数据库的要求。

我正在使用URLClassLoader加载jar文件

File f = new File("D:/Pallavi/workspace/WarInstallation/mysql-connector-java-5.0.4-bin.jar"); //Jar path

URLClassLoader urlCl = new URLClassLoader(new URL[] { f.toURL()},System.class.getClassLoader()); 
Class sqldriver = urlCl.loadClass("com.mysql.jdbc.Driver"); // Runtime loading

Driver ds = (Driver) sqldriver.newInstance(); //Compilation failing as "sqldriver" class of type Driver is not found

//I am using now java.sql.Driver to remove the compilation error

sqldriver = Class.forName("com.mysql.jdbc.Driver", true, sqldriver.getClassLoader()).newInstance(); //Runtime fail.. "Driver" Class not Found Exception.

虽然类加载正常,但无论我尝试使用哪种驱动程序,都无法建立数据库连接(找不到合适的驱动程序...)。

请建议一种加载jdbc“com.mysql.jdbc.Driver”类运行时的方法。 如果您需要任何进一步的信息,请告诉我,因为这很紧急。

提前致谢。

2 个答案:

答案 0 :(得分:1)

在回答你的问题之前,我有三个问题:

  1. 声明1

    ya, I have set the classpath of mysql jar in the environment variables, do we need to set it through system properties?

    Q1 :当类路径中的类类加载器可以使用类时,为什么要依赖自定义类加载器?
    您不需要mysql***.jar的显式类路径来使用自定义类加载器。

  2. 声明2

    Class sqldriver = urlCl.loadClass("com.mysql.jdbc.Driver"); // Runtime loading
    //Compilation failing as "sqldriver" class of type Driver is not found
    Driver ds = (Driver) sqldriver.newInstance();

    Q2 :声称​​ Compilation failing ... 非常矛盾。你的编译器是否正在寻找这样的类来生成你的类! 我相信不是。可能是错误是在运行时java.lang.ClassNotFoundException: com.mysql.jdbc.Driver。我还怀疑评论应该与你下面的声明3 一致 如果是CNFE,则mysql***.jar的文件路径是错误的。先修复它。

  3. 声明3

    //I am using now java.sql.Driver to remove the compilation error
    //Runtime fail.. "Driver" Class not Found Exception. sqldriver = Class.forName("com.mysql.jdbc.Driver", true, sqldriver.getClassLoader()).newInstance();

    Q3 :声称​​ ... "Driver" Class not Found Exception 是可疑的。因为,这个语句不会被编译。那怎么可能是运行时失败。 .. !?
    我还怀疑评论应该与上面的声明2 一致 在这里,您需要拨打newInstance(),然后转到java.sql.Driver,然后再分配到sqlDriver变量。因为Class.forName( ...只返回Class object associated with the class or interface with the given string name 如果修复了上述 Statement 2 的问题,则可以应用此修复程序进一步测试。

  4. 我希望你澄清这些陈述。


    我在下面有一个工作示例代码,并为您显示测试输出。

    import java.io.File; // and others as required
    
    public class MySQLDriveClassLoader {
      public static void main( String [] args ) throws Exception {
        //File f = new File( "/home/ravinder/soft-dump/mysql-connector-java-5.1.18-bin.jar" );
        File f = new File( "E:\\Soft_Dump\\mysql-connector-java-5.0.4\\mysql-connector-java-5.0.4-bin.jar" );
        URLClassLoader urlCl = new URLClassLoader( new URL[] { f.toURI().toURL() }, System.class.getClassLoader() );
    
        Class mySqlDriver = urlCl.loadClass( "com.mysql.jdbc.Driver" );
    
        //*** Start: DEBUG *************************
        //mySqlDriver.con // On pressing CTRL+SPACEBAR, after .con, IDE shows "No default proposals"
        // meaning it still is not an instance of Driver, and hence can't call a method from Driver class.
    
        //Incompatible conditional operand types Class and Driver
        //System.out.println( mySqlDriver instanceof java.sql.Driver ) );
    
        System.out.println( "mySqlDriver: " + mySqlDriver );
        System.out.println( "Is this interface? = " + mySqlDriver.isInterface() );
    
        Class interfaces[] = mySqlDriver.getInterfaces();
        int i = 1;
        for( Class _interface : interfaces ) {
          System.out.println( "Implemented Interface Name " + ( i++ ) + " = " + _interface.getName() );
        } // for(...)
    
        Constructor constructors[] = mySqlDriver.getConstructors();
        for( Constructor constructor : constructors ) {
          System.out.println( "Constructor Name = " + constructor.getName() );
          System.out.println( "Is Constructor Accessible? = " + constructor.isAccessible() );
        } // for(...)
        //*** End  : DEBUG *************************
    
        Driver sqlDriverInstance = ( Driver ) mySqlDriver.newInstance();
        System.out.println( "sqlDriverInstance: " + sqlDriverInstance );
    
        Connection con = null;
        try {
          /******************************************************************
          // You may fail to register the above driver
          // hence don't depend on DriverManager to get Connected
          //DriverManager.registerDriver( sqlDriverInstance );
          //Driver driver = DriverManager.getDriver( "com.mysql.jdbc.Driver" ); // ( "jdbc:mysql" );
          Enumeration<Driver> enumDrivers = DriverManager.getDrivers();
          while ( enumDrivers.hasMoreElements() ) {
            Driver driver = enumDrivers.nextElement();
            System.out.println( "driver: " + driver );
          } // while drivers
          //******************************************************************/
    
          String dbUrl = "jdbc:mysql://:3306/test";
          Properties userDbCredentials = new Properties();
          userDbCredentials.put( "user", "root" );
          userDbCredentials.put( "password", "password" );
    
          // No suitable driver found for ...
          //con = DriverManager.getConnection( dbUrl, "root", "password" );
    
          // safely use driver to connect
          con = sqlDriverInstance.connect( dbUrl, userDbCredentials );
          System.out.println( "con: " + con );
    
          Statement stmt = con.createStatement();
          String sql = "select now()";
          ResultSet rs = stmt.executeQuery( sql );
          if ( rs.next() ) {
            System.out.println( rs.getString( 1 ) );
          } // if rs
        } catch( Exception e ) {
          e.printStackTrace(); // only for quick debug
        } finally {
          try { if ( con != null ) con.close(); } catch ( Exception ignoreThis ) {}
        }
      } // psvm(...)
    } // class MySQLDriveClassLoader
    

    成功编译并运行,结果如下:

    mySqlDriver: class com.mysql.jdbc.Driver
    Is this interface? = false
    Implemented Interface Name 1 = java.sql.Driver
    Constructor Name = com.mysql.jdbc.Driver
    Is Constructor Accessible? = false
    sqlDriverInstance: com.mysql.jdbc.Driver@1270b73
    con: com.mysql.jdbc.Connection@32fb4f
    2012-05-29 03:52:12.0
    

答案 1 :(得分:0)

DriverManager忽略在运行时加载的类,它只适用于由System类加载器加载的类。

您可以创建一个Dummy驱动程序类,它封装了您的实际数据库驱动程序。可以找到源代码here

非主题:

不推荐使用

File.toURL,而是使用File上的toURLURI获取网址

URLClassLoader urlCl = new URLClassLoader(new URL[] { f.toURI().toURL()},System.class.getClassLoader());