Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to register jdbc driver into DriverManager? #109

Open
Rokkregin opened this issue Dec 29, 2024 · 2 comments
Open

how to register jdbc driver into DriverManager? #109

Rokkregin opened this issue Dec 29, 2024 · 2 comments
Assignees
Labels
bug Something isn't working

Comments

@Rokkregin
Copy link

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?

@MarkusJx
Copy link
Owner

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 MarkusJx self-assigned this Dec 31, 2024
@MarkusJx MarkusJx added the bug Something isn't working label Dec 31, 2024
@MarkusJx
Copy link
Owner

MarkusJx commented Jan 2, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants