node-java-bridge icon indicating copy to clipboard operation
node-java-bridge copied to clipboard

how to register jdbc driver into DriverManager?

Open Rokkregin opened this issue 1 year ago • 2 comments

I want to connect mysql via jdbc. I've appended mysql connector to classpath and import com.mysql.cj.jdbc.Driver, then import java.sql.DriverManager and register mysql Driver with method DriverManager.registerDriverSync. but I can't find any driver by using DriverManager.getDeiversSync,and can't find suitable driver for jdbc url either. how can I use jdbc with node - java-bridge?

Rokkregin avatar Dec 29 '24 09:12 Rokkregin

I just tried connecting to a mysql database and ran into the same issue. I'll try to figure out what's wrong and get back to you once I know why this isn't working.

MarkusJx avatar Dec 31 '24 12:12 MarkusJx

I've looked further into this and found the following:

  • DriverManager.getDriver(String url) uses Reflection.getCallerClass() to get the caller class and check if the class loader of the caller class is able to load the driver
  • Since we are calling java from node, there is no caller class, Reflection.getCallerClass() will return null
  • If no caller class is passed, Class.forNameSync("com.mysql.cj.jdbc.Driver", true, null) will be called to check if the driver exists
  • If null is passed as a third argument to Class.forNameSync, the bootstrap class loader will be used to search for the driver and won't find anything since the bootstrap class loader only contains the java runtime classes
  • This will cause DriverManager.getDriver to not find an appropriate driver

The easiest fix for this would be to encapsulate your java logic in a java class, load this class and call the methods from it using java-bridge. This will ensure Reflection.getCallerClass() to return a proper java class and since java-bridge sets the class loader properly, the driver will be found.

MarkusJx avatar Jan 02 '25 16:01 MarkusJx

Closing due to inactivity

MarkusJx avatar Oct 31 '25 18:10 MarkusJx