The Infamous No Suitable Driver Found For JDBC and how to fix it

Advertisements

This error is a very common error when the code doing JDBC connections to the database in runtime. Since the JDBC API is part of the JDK, the code will compile without any issue, but when the application runs it might trigger that error. Remember JDBC API only provides the interface (the contract) but without any specific implementation. The implementations will depend on the database engine the application needs to connect like MySQL, Postgres, Oracle, DB2, SQL Server, etc.

And that’s a Driver, it’s just a library (jar file) which implements de JDBC API for one specific database.

When using JDBC to connect a database in a Java application, two things needs to be done before creating the connection to the database.

  • Add the driver (jar file) in the classpath of your application. This can be done with options of the IDE or if using Maven/Gradle by adding the dependency
  • Register the driver before calling the DriverManager.getConnection method by first time.

If any of those pre-requisites are not done, then the exception java.sql.SQLException: No suitable driver found for jdbc: will be thrown.

Advertisements

How to register the Driver?

It’s very easy, it only needs to add the following line before creating the connection.

// load and register JDBC driver for MySQL 
Class.forName("com.mysql.jdbc.Driver");

The String value of the forName method will depend on the database engine to connect. Those are the most common values.

Class.forName("oracle.jdbc.driver.OracleDriver");   // For Oracle 
Class.forName("org.postgresql.Driver");   			// For Postgress
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  // For MS-SQL Server
Class.forName("com.mysql.jdbc.Driver");				// For MySQL
Class.forName("com.ibm.db2.jcc.DB2Driver");			// For IBM DB2
Class.forName("org.mariadb.jdbc.Driver");   		// For MariaDB           

This one example, of code registering the Driver before creating the connection.

public class Main { 
  public static void main(String[] args) { 
  Connection dbConnection = null; 
    try { 
      String url = "jdbc:mysql://localhost:3306/test"; 
      Properties info = new Properties(); 
      info.put("user", "root"); 
      info.put("password", "test"); 
      
      Class.forName("com.mysql.jdbc.Driver");   //Registering the driver
      dbConnection = DriverManager.getConnection(url, info); 
      if (dbConnection != null) { 
        System.out.println("Successfully connected to MySQL database test"); 
      } 
    } catch (SQLException ex) { 
      System.out.println("An error occurred while connecting MySQL databse"); 
      ex.printStackTrace(); 
    } 
  } 
}

References

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *