0

I have a plugin that connects to database. I don't want to bundle the jar for the driver in my plugin. Instead i want to take it from the users project and load it in run-time. Below is the code I am using to achieve the same. I get the error "No suitable driver found......" Please point out what could be wrong.

jPrj -- is the IJavaProject object,of the project from where i want to load the driver class. databaseType -- "mysql"

final String[] classPathEntries = JavaRuntime.computeDefaultRuntimeClassPath(jPrj);
for (int i = 0; i < classPathEntries.length; i++) {
    final String entry = classPathEntries[i];
    if (entry.contains(databaseType)) {
        final IPath path = new Path(entry);
        final URL url = path.toFile().toURI().toURL();
        urlList.add(url); //the value of url at this point is-- file:/C:/.../mysql-connector-java-5.1.15-bin.jar -- the path on my disk
        final ClassLoader parentClassLoader = jPrj.getClass().getClassLoader();
        final URL[] urls = urlList.toArray(new URL[urlList.size()]);
        final URLClassLoader classLoader = new URLClassLoader(urls, parentClassLoader);
        try {
            final ClassLoader loader = new URLClassLoader(urls);
            loader.loadClass("com.mysql.jdbc.Driver"); 
            Class<?> clazz = loader.loadClass("java.sql.DriverManager");
        } catch (final ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        break;
    }
}
DriverManager.getConnection("jdbc:mysql://localhost:port/myDB", myuser, mypaswrd); //-- get exception from here

I m not sure how to use clazz for the DriverManager.getConnection

Krishnaveni
  • 799
  • 2
  • 11
  • 32
  • Are you sure that your exception is thrown from line `Class.forName(...)`? – AlexR Jun 22 '14 at 13:33
  • No, this line works, the exception comes from DriverManager.getConnection(.......)...also i am not supposed to use Class.forName instead i need to use the loder.loadClass...even in that case the DriverManager.getConnection gives the exception – Krishnaveni Jun 23 '14 at 01:26

1 Answers1

0

In this case take a look on the following discussion.

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

I believe that your case is similar. Double check the JDBC URL that you are using.

BTW please pay attention that your does not contain code that actually throws exception (DriverManager.getConnection()) and that its subject is absolutely confusing. If you re-define your subject like "No suitable driver found during JDBC connection" you can find the linked discussion within a second.

Community
  • 1
  • 1
AlexR
  • 114,158
  • 16
  • 130
  • 208
  • My code works if i add the required jars in my plugin and use Class.forName() and DriverManager.getConnection....I want to get it working without having to bundle that jar with the plugin, instead load it from the project class path – Krishnaveni Jun 23 '14 at 08:53