Adding the MySQL driver with Maven
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A JDBC program fails to connect when the vendor's driver is not on its classpath. In a Maven project, how do you add the MySQL driver, and how do you check that it is really there?
The mysql-connector-j dependency and choosing its version
MySQL Connector/J is MySQL's official JDBC driver. On Maven Central its coordinates are groupId com.mysql and artifactId mysql-connector-j.
Add the driver to pom.xml as one dependency block. Maven downloads it on the next build.
Example 1 · pom.xml (the dependencies section)
Runs in: the shoplite-console Maven project
<dependencies> <!-- MySQL JDBC driver: needed only when the program runs --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>26.7.0</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.14.4</version> <scope>test</scope> </dependency></dependencies>$ mvn compile ... Downloading from central: https://repo.maven.apache.org/maven2/com/mysql/mysql-connector-j/26.7.0/mysql-connector-j-26.7.0.pom Downloaded from central: https://repo.maven.apache.org/maven2/com/mysql/mysql-connector-j/26.7.0/mysql-connector-j-26.7.0.pom (3.2 kB at 48 kB/s) Downloading from central: https://repo.maven.apache.org/maven2/com/google/protobuf/protobuf-java/4.31.1/protobuf-java-4.31.1.pom Downloaded from central: https://repo.maven.apache.org/maven2/com/google/protobuf/protobuf-java/4.31.1/protobuf-java-4.31.1.pom (1.6 kB at 24 kB/s) Downloading from central: https://repo.maven.apache.org/maven2/com/google/protobuf/protobuf-parent/4.31.1/protobuf-parent-4.31.1.pom Downloaded from central: https://repo.maven.apache.org/maven2/com/google/protobuf/protobuf-parent/4.31.1/protobuf-parent-4.31.1.pom (9.3 kB at 146 kB/s) Downloading from central: https://repo.maven.apache.org/maven2/com/google/protobuf/protobuf-bom/4.31.1/protobuf-bom-4.31.1.pom Downloaded from central: https://repo.maven.apache.org/maven2/com/google/protobuf/protobuf-bom/4.31.1/protobuf-bom-4.31.1.pom (3.7 kB at 72 kB/s) Downloading from central: https://repo.maven.apache.org/maven2/com/mysql/mysql-connector-j/26.7.0/mysql-connector-j-26.7.0.jar Downloaded from central: https://repo.maven.apache.org/maven2/com/mysql/mysql-connector-j/26.7.0/mysql-connector-j-26.7.0.jar (2.6 MB at 3.0 MB/s) Downloading from central: https://repo.maven.apache.org/maven2/com/google/protobuf/protobuf-java/4.31.1/protobuf-java-4.31.1.jar Downloaded from central: https://repo.maven.apache.org/maven2/com/google/protobuf/protobuf-java/4.31.1/protobuf-java-4.31.1.jar (1.9 MB at 1.1 MB/s) ... [INFO] BUILD SUCCESS
What this code does
- The new
<dependency>block names the driver by groupId, artifactId and version, withruntimescope. JUnit stays as it was, withtestscope. - On the first build Maven downloads the driver's pom and JAR, plus
protobuf-java, which the driver depends on. Later builds use the copies in~/.m2/repositoryand print nothing.
For the version, search Maven Central for mysql-connector-j and take the newest release; it was 26.7.0 when this lesson was written. MySQL switched the driver to year-based version numbers. Recent releases work with MySQL 8.0 and later, so they suit the MySQL 8.4 LTS server from the SQL section. Do not copy a version from an old blog post: old drivers miss security fixes and newer login methods.
Old tutorials use groupId mysql and artifactId mysql-connector-java. Those coordinates stopped at 8.0.33 and now only point to the new name. Maven warns: The artifact mysql:mysql-connector-java:jar:8.0.33 has been relocated to com.mysql:mysql-connector-j:jar:8.0.33, and you are stuck on an old driver. Always use com.mysql:mysql-connector-j.
Runtime scope: your code compiles against java.sql only
Runtime scope means a dependency is on the classpath when the program runs and when tests run, but not when your main code is compiled.
Compile a class that imports the driver's own class while the driver has runtime scope.
Example 2 · src/main/java/com/shoplite/app/OldStyleConnect.java
Runs in: the shoplite-console Maven project
package com.shoplite.app;
import com.mysql.cj.jdbc.Driver; // a driver class, not java.sql
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;
public class OldStyleConnect { public static void main(String[] args) throws SQLException { DriverManager.registerDriver(new Driver()); try (Connection conn = DriverManager.getConnection(System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { System.out.println("Connected"); } }}$ mvn compile ... [ERROR] COMPILATION ERROR : [ERROR] /C:/Users/asha/shoplite-console/src/main/java/com/shoplite/app/OldStyleConnect.java:[3,25] package com.mysql.cj.jdbc does not exist [ERROR] /C:/Users/asha/shoplite-console/src/main/java/com/shoplite/app/OldStyleConnect.java:[11,42] cannot find symbol symbol: class Driver location: class com.shoplite.app.OldStyleConnect [INFO] BUILD FAILURE
What this code does
- With
runtimescope the compiler cannot see anycom.mysqlpackage, so the import fails withpackage com.mysql.cj.jdbc does not exist. - The fix is to delete the import and the
registerDriverline.DriverManager.getConnectionfinds the driver by itself, and the class then depends only onjava.sql.
A dependency's scope says when Maven puts it on the classpath, the list of places Java looks for classes. That fits a JDBC driver: your code uses only java.sql types, which are in the JDK, so the compiler never needs the driver, and the mistake is caught before it ties ShopLite to MySQL-only classes.
The default compile scope would also work; nothing breaks at run time. runtime is simply the stricter, cleaner choice, and Spring Boot projects use it for drivers too.
Automatic driver loading, and why Class.forName is no longer needed
ServiceLoader is a JDK class that finds implementations of an interface listed in META-INF/services files inside JARs. The MySQL driver JAR lists com.mysql.cj.jdbc.Driver in META-INF/services/java.sql.Driver.
Old tutorials loaded the driver by hand before connecting. Today one line is enough.
Class.forName("com.mysql.cj.jdbc.Driver"); // works, but not needed any moreClass.forName("com.mysql.jdbc.Driver"); // old name: prints a deprecation warning
Connection conn = DriverManager.getConnection(url, user, password); // the driver registers itselfExample 3 · src/main/java/com/shoplite/app/ListDrivers.java
Runs in: the shoplite-console Maven project
package com.shoplite.app;
import java.io.IOException;import java.io.InputStream;import java.nio.charset.StandardCharsets;import java.sql.DriverManager;
public class ListDrivers { public static void main(String[] args) throws IOException { System.out.println("Drivers that DriverManager found:"); DriverManager.drivers() .forEach(d -> System.out.println(" " + d.getClass().getName() + " " + d.getMajorVersion() + "." + d.getMinorVersion()));
String file = "META-INF/services/java.sql.Driver"; try (InputStream in = ListDrivers.class.getClassLoader().getResourceAsStream(file)) { System.out.println("The driver JAR's " + file + " file says:"); System.out.println(" " + new String(in.readAllBytes(), StandardCharsets.UTF_8).trim()); } }}Drivers that DriverManager found: com.mysql.cj.jdbc.Driver 26.7 The driver JAR's META-INF/services/java.sql.Driver file says: com.mysql.cj.jdbc.Driver
What this code does
DriverManager.drivers()lists the registered drivers. The MySQL driver is there although the program never loads it:ServiceLoaderfound it through the services file.- The second part reads that services file straight from the driver JAR. Its single line is the class name
DriverManagerregisters. The version printed depends on the driver you use.
The first time you use DriverManager, it asks ServiceLoader for every java.sql.Driver on the classpath and registers each one. This has worked since JDBC 4.0 (Java 6), so you never load the driver yourself.
With the old name, the driver prints Loading class 'com.mysql.jdbc.Driver'. This is deprecated. The new driver class is 'com.mysql.cj.jdbc.Driver'. Delete such lines when you see them.
'No suitable driver found': missing dependency or a mistyped URL
Four URLs run in a project that has the driver: one is right and three have a typo.
Example 4 · src/main/java/com/shoplite/app/WrongUrls.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.app;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;
public class WrongUrls { public static void main(String[] args) { String user = System.getenv("DB_USER"); String password = System.getenv("DB_PASSWORD"); String base = "jdbc:mysql://localhost:3306/shoplite"; String[] urls = { base, base.replace("mysql", "mysq"), base.replace("jdbc:", ""), base.replace("mysql:", "mysql") }; for (String url : urls) { try (Connection conn = DriverManager.getConnection(url, user, password)) { System.out.println("OK " + url); } catch (SQLException e) { System.out.println("FAILED " + url); System.out.println(" " + e.getMessage()); } } }}OK jdbc:mysql://localhost:3306/shoplite
FAILED jdbc:mysq://localhost:3306/shoplite
No suitable driver found for jdbc:mysq://localhost:3306/shoplite
FAILED mysql://localhost:3306/shoplite
No suitable driver found for mysql://localhost:3306/shoplite
FAILED jdbc:mysql//localhost:3306/shoplite
No suitable driver found for jdbc:mysql//localhost:3306/shopliteWhat this code does
- The driver is loaded in this project, yet three URLs fail with
No suitable driver found. Thereplacecalls make the typos:mysqfor the product name, nojdbc:prefix, and no:before//. - The message repeats the URL exactly, so copy it from the error and compare it character by character with
jdbc:mysql://host:port/database.
No suitable driver found for <url> means that no loaded driver accepted the URL. It has exactly two causes, and the message does not say which one.
The first cause: the driver is not on the classpath. The dependency is missing from pom.xml, the IDE has not reloaded the pom, the scope is test, or the program was started with a plain java -cp target/classes ... command that leaves out the driver JAR. The second cause: the URL is mistyped, so the driver is loaded but says "not mine", as in this example. Check them in that order: is the driver loaded (Example 3 lists it), and does the URL start exactly with jdbc:mysql://?
Find the bug
Find the line behind the error
Tap the line that causes "No suitable driver found" or the Maven warning.
The build works, but the program says No suitable driver found.
Checking the driver is on the classpath with dependency:tree
A transitive dependency is a library that one of your dependencies needs, which Maven adds automatically. The MySQL driver brings protobuf-java this way.
Print the dependency tree and look for the driver line.
Example 5 · Checking the driver with mvn dependency:tree
Runs in: the shoplite-console Maven project
mvn dependency:treemvn dependency:tree -Dincludes=com.mysql$ mvn dependency:tree [INFO] --- dependency:3.6.1:tree (default-cli) @ shoplite-console --- [INFO] com.shoplite:shoplite-console:jar:0.1.0-SNAPSHOT [INFO] +- com.mysql:mysql-connector-j:jar:26.7.0:runtime [INFO] | \- com.google.protobuf:protobuf-java:jar:4.31.1:runtime [INFO] \- org.junit.jupiter:junit-jupiter:jar:5.14.4:test [INFO] +- org.junit.jupiter:junit-jupiter-api:jar:5.14.4:test [INFO] | +- org.opentest4j:opentest4j:jar:1.3.0:test [INFO] | +- org.junit.platform:junit-platform-commons:jar:1.14.4:test [INFO] | \- org.apiguardian:apiguardian-api:jar:1.1.2:test [INFO] +- org.junit.jupiter:junit-jupiter-params:jar:5.14.4:test [INFO] \- org.junit.jupiter:junit-jupiter-engine:jar:5.14.4:test [INFO] \- org.junit.platform:junit-platform-engine:jar:1.14.4:test [INFO] BUILD SUCCESS
What this code does
- The driver line ends in
:runtime, its own dependencyprotobuf-javais indented below it, and JUnit with its parts is marked:test. -Dincludes=com.mysqlkeeps only the lines whose groupId iscom.mysql, which is handy once the project uses many libraries.
mvn dependency:tree prints every library the project uses, with the libraries each one brings in indented below it. Each line ends with the scope.
Look for com.mysql:mysql-connector-j:jar:<version>:runtime. If that line is missing, the dependency is not in this pom; if the version is not the one you wrote, another library or an older entry wins. protobuf-java is used only by the driver's X DevAPI feature, so you can ignore it. In IntelliJ IDEA, the Maven tool window's Dependencies node shows the same tree.
Order of execution
Debugging "No suitable driver found"
Tap the steps in the order you would check them.
Next step
Check your understanding
11 quick questions