Christian Kammerer
Christian Kammerer

Reputation: 175

No suitable driver found when exporting to a JAR-file?

I am trying to get my project into a JAR so I can run it as a CLI. I have two JDBC connectors that I am using, one for MySQL one for PostgreSQL. Both are located in the same directory and work fine if I run them in the IDE. When I create the JAR the MySQL connector still works fine, however when trying to establish a connection to PostgreSQL the following error appears. Terminal output when running my jar What really irritates me is that the connector seems to be included in the build of the jar. enter image description here Both the MySQL connector and PostgreSQL connector are listed in the build. How can I go about fixing this?

Upvotes: 0

Views: 1138

Answers (1)

Mark Rotteveel
Mark Rotteveel

Reputation: 108927

The problem is that all JDBC-4-compliant JDBC drivers contain a file /META-INF/services/java.sql.Driver that lists the java.sql.Driver implementations in the JAR files. This is used by the java.sql.DriverManager to load the available JDBC drivers.

The process you used for merging apparently doesn't merge the different files from the drivers into a single file, so it only has the content of one of the drivers. As a result, the other driver isn't loaded automatically.

Possible solutions:

  1. Don't merge JAR files into a single JAR, but instead use the Class-Path attribute of META-INF/MANIFEST.MF to specify the JARs you use, and execute your program with java -jar your.jar
  2. Make sure META-INF/services/java.sql.Driver is merged correctly (or maybe provide your own), depending on how you merge, there might be an option to configure which files need to be merged
  3. Explicitly load the drivers using Class.forName("com.mysql.cj.jdbc.Driver") and Class.forName("org.postgresql.Driver") (do it for both to prevent problems if order of merging files changes, and the other file wins)

Upvotes: 1

Related Questions