How can I find all JDBC drivers available?
Asked Answered
C

2

1

I have a library method that can be used to connect to a database and then build a document using data from the database.

When they run this app with no parameters, I want to list out all available sql vendor connections. Based on this question I'm guessing its done using ServiceLoader but it's not clear to me exactly how to do this.

And critical to this is I'd like to get the class "com.mysql.jdbc.Driver", and I must get the "jdbc:mysql:" start of the connection string syntax.

So, how can I get the class (optional) and connection string start (necessary) of all JDBC connectors in the classpath?

Clyte answered 5/1, 2020 at 19:37 Comment(3)
@user85421 Unfortunately this doesn't provide the "jdbc"mysql:" syntax info.Clyte
You certainly can use ServiceLoader.load(Driver.class) or DriverManager.drivers() to list the drivers, but as far as I know, there is no way to automatically determine the syntax for a driver’s JDBC URLs.Palestra
ServiceLoader or DriverManager.getDrivers() is great; a list of URLs you must obtain from elsewhere like benchresources.net.Fascicule
M
1

There is no way defined in JDBC to automatically discover the JDBC URL format of a driver.

You will need to keep a registry of JDBC URL formats yourself (eg linked to one or more drivers), and then using the ServiceLoader or DriverManager, discover the available drivers and use that to determine which URL formats you can use.

Be aware that JDBC allows multiple drivers to use the same JDBC URL format (the first driver to successfully connect 'wins'), and a single driver can have more than one JDBC URL format.

To discover the JDBC drivers on the classpath, you can use

ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
for (Driver driver : loadedDrivers) {
    // do something with Driver
}

Be aware that using for-each might not be the best solution. Explicitly using the iterator might be better as then you can explicitly handle the ServiceConfigurationError thrown if a specific driver fails to load.

Alternatively, you can use

Enumeration<Driver> drivers = DriverManager.getDrivers();

And let DriverManager take care of discovering the drivers.

Mccord answered 6/1, 2020 at 12:5 Comment(0)
R
-1

Maybe you can use a framework, which abstracts the layer of data access i.e. all the talking to the database?

I could recommend you Spring Data JDBC. https://spring.io/projects/spring-data-jdbc

But there are more frameworks that you could find as OR-Mapper which could help you.

Ramburt answered 6/1, 2020 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.