In this post, we will see how to resolve java.sql.SQLException: No suitable driver found for JDBC
.
There can be multiple reasons for this exception and let’s see it one by one.
Table of Contents
connector jar is not on classpath
you need make sure you have connector jar
on classpath.
For example:
If you are using mysql
to connect to database, then mysql-connector-java
jar should on classpath.
You can add the maven dependency as below:
1 2 3 4 5 6 7 8 |
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency> |
You can find versions of jar over here.
Jar not present in Tomcat/JBoss lib
If you are using web servers such as tomcat
or JBoss
, then you should put the connector jar in server lib folder
.
For example:
In case you are using tomcat and mysql, you should put mysql-connector-java
in $CATALINA_HOME/lib
.
Actually, the connection pool needs to be set up before application is instantiated. This could be the reason, you need to put jar in server lib folder.
If you are using eclipse to run tomcat, then eclipse won’t pick $CATALINA_HOME/lib
.
You can fix this issue in two ways:
- Click on
Open Launch Config
->classpath tab
to set mysql-connector-java jar on classpath. - Go to server tab and select option
Use Tomcat installation
Typo in connection url
This exception can also arise if you have typo in your jdbc url
.
For example:
Let’s say if you have jdbc URL
as below.
If you notice closely, we are missing :
after mysql and URL should be
Did not call class.forName() [old java versions]
If you are using java version less than 6
or did not use JDBC 4.0 compliant connector jar
, then you can get this exception.
You need to register driver before calling DriverManager.getConnection()
;
Let’s understand with the help of example:
1 2 3 4 5 6 7 8 |
Connection con = null; try { con = DriverManager.getConnection("jdbc:mysql//localhost:3307/dbname"); } catch (SQLException e) { throw new RuntimeException(e); } |
Above code will give error because we did not call Class.forName()
before calling DriverManager.getConnection().
You can fix the error with:
1 2 3 4 5 6 7 8 9 10 |
Connection con = null; try { //registering the jdbc driver here Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql//localhost:3307/dbname"); } catch (SQLException e) { throw new RuntimeException(e); } |
If you are using Java 6 or above and the latest version of mysql-connector-java, then you should not get this exception because of Class.forName()
Conclusion
As you can see, there can be multiple reason for getting java.sql.SQLException: No suitable driver found for JDBC
. You need to identify which can applicable in your application.
That’s all about how to fix no suitable driver found for jdbc error. If you are still facing this issue, please comment.