Below is the procedure to establish connection with the database server.

  1. Register the driver with driver manager
  2. Call drivermanager.get connection() method to establish the connection with the server.

Example to establish a connection with MYSQL DB:
Add the mysql-connector-java-3.0.11-stable-bin.jar jar file to the class-path.

import java.sql.*;
public class MysqlDBConnection{
public static void main(String[] args) throws Exception{
  Driver drv = new com.mysql.jdbc.Driver();
  DriverManager.registerDriver(drv);
 Connection con = DriverManager.getConnection(
 "jdbc:mysql://localhost:3306/test",
 "userName",
 "password");
System.out.println("Connection:"+ con.getClass());
//code to deal with DB
con.close();
}
}

Example to connect Oracle Database:
Add the ojdbc14.jar jar file to the class-path.

import java.sql.*;
public class OracleDBConnection{
public static void main(String[] args) throws Exception{
 Driver drv = new oracle.jdbc.driver.OracleDriver();
 DriverManager.registerDriver(drv);
 Connection con = DriverManager.getConnection(
    "jdbc:oracle:thin:@localhost:1521:XE",
    "userName",
    "password");
 System.out.println("Connection:"+ con.getClass());
//code to deal with DB
con.close();
}
}

According to the JDBC specification,the JDBC driver vendor must provide a static block in the driver class. The code in the static block must take care of registering the driver with the drivermanager.

Class.forName("oracle.jdbc.driver.OracleDriver");

When the above statement is executed the driver class oracle.jdbc.driver.OracleDriver will be loaded and the JVM executes the static block. The code in the static block registers the driver with the DriverManager.

Now we can replace below 2 statements with Class.forName("oracle.jdbc.driver.OracleDriver");
Driver drv = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(drv);