Is it mandatory to register the driver while working with JDBC?


Initially, till Java6 it is needed to register the driver using Class.forname() or the registerDriver() method before establishing connection with the database.

But, since Java 1.6, JDBC 4.0 API, there is no need to register the driver explicitly, You Just need to set the Class path for the JDBC 4.X driver, Java automatically detects the Driver class and loads it.

Example

In the following JDBC program we are trying connect with MySQL database first of all include the dependency for the MySQL driver in the pom.xml of your project.

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>8.0.16</version>
</dependency>

Then, without registering the MySQL driver class com.mysql.jdbc.Driver we are trying to invoke the getConnection object.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class RunningScripts {
   public static void main(String args[]) throws SQLException {
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/talakai_noppi";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established: "+ con);
   }
}

Output

Soon we execute this JVM automatically detects the MySQL driver and loads it automatically and this program executes successfully and generates the following output −

Connection established: com.mysql.jdbc.JDBC4Connection@424c0bc4

Updated on: 30-Jul-2019

499 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements