2
votes

I am trying to have an OSGI bundle access a MYSQL DB, using Eclipse as my IDE (Windows 7 x64). I am able to load the jdbc connector. The actual .jar is placed in all \bin folders in the java install directories, along with the \bin folder of the bundle. I have set the environment classpath variable to this folder also. I have an error stating that the driver is not suitable. I know OSGI has some issues with drivers etc. Can someone recommend a way to circumvent this?

ClassLoader DBHCL = ClassLoader.getSystemClassLoader();
DBHCL.loadClass("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver", true, DBHCL).newInstance();
System.out.println("Class Loaded");
//DriverManager.getDriver("jdbc:mysql://localhost/timedb");
//System.out.println("Driver Gotten");
conn = DriverManager.getConnection(URL + DBName,username,password);
System.out.println("Connection Created");
stmt = conn.createStatement();
System.out.println("Statement Created");
connFlag = true;

Console Output, Error: osgi> start 7 Data Base Service (MYSQL) Starting Class Loaded No suitable driver found for jdbc:mysql://localhost/timedb Exception in thread "Thread-1" INSERT INTO appliance1...

Does anybody have any insight into this problem?

I have tried making a separate bundle solely for the jdbc driver and exporting/importing this to the appropriate bundle, but no luck.

Thanks

1

1 Answers

3
votes

In your code snippet, you get the SystemClassLoader, and you ask it for the "com.mysql.jdbc.Driver". Given that that call doesn't give you a ClassNotFoundException, we can conclude the system classloader can find the class for you; the driver will then register itself to the DriverManager.

However, you don't see the same DriverManager that the MySQL driver does! The MySQL driver sees the one from the system classloader, but your code (conn = DriverManager. ...) uses the one from the bundle's own classloader. These are two different classes, hence, no suitable driver is found.

My solution would be to not use the SystemClassLoader (which you shouldn't do in OSGi anyway, unless you know exactly what you're doing), but use the bundle's classloader. So, I would

  • not put the MySQL jar on the system classpath, but let OSGi do the hard work. You can put the jar in a bundle, and put the jar on the Bundle-ClassPath. You can then choose either to keep it private to your bundle (if you're the only one using it), or export the packages.
  • In stead of using the system classloader, use the bundle's classloader. This can be as simple as using Class.forName("com.mysql.jdbc.Driver"); this will do the right thing.