JDBC Class.forName vs DriverManager.registerDriver


To connect with a database using JDBC you need to select get the driver for the respective database and register the driver. You can register a database driver in two ways −

Using Class.forName() method − The forName() method of the class named Class accepts a class name as a String parameter and loads it into the memory, Soon the is loaded into the memory it gets registered automatically.

Class.forName("com.mysql.jdbc.Driver");

Example

Following JDBC program establishes connection with MySQL database. Here, we are trying to register the MySQL driver using the forName() method.

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

Output

Connection established: com.mysql.jdbc.JDBC4Connection@4fccd51b

Using the registerDriver() method − The registerDriver() method of the DriverManager class accepts an object of the diver class as a parameter and, registers it with the JDBC driver manager.

Driver myDriver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(myDriver);

Example

Following JDBC program establishes connection with MySQL database. Here, we are trying to register the MySQL driver using the registerDriver() method.

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

Output

Connection established: com.mysql.jdbc.JDBC4Connection@4fccd51b

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements