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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • @user85421 Unfortunately this doesn't provide the "jdbc"mysql:" syntax info. – David Thielen Jan 05 '20 at 19:41
  • 1
    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. – VGR Jan 05 '20 at 22:23
  • ServiceLoader or DriverManager.getDrivers() is great; a list of URLs you must obtain from elsewhere like [**benchresources.net**](https://www.benchresources.net/jdbc-driver-list-and-url-for-all-databases/). – Joop Eggen Jan 06 '20 at 12:32

2 Answers2

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
0

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.

Tobias Otto
  • 1,634
  • 13
  • 20