How to establish connection with JDBC?


To connect with a database, you need to follow the steps given below:

Step1: Register the driver: To develop a basic JDBC application, first of all, you need to register the driver with the DriverManager.

You can register a driver in two ways, one is using registerDriver() method of the DriverManager class and, using forName() method of the class named Class.

The registerDriver() method accepts an object of the Driver class, it registers the specified Driver with the DriverManager.

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

The forName() method loads the specified class into the memory and thus it automatically gets registered.

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

Step2: Get Connection: Get the Connection object using the getConnection() method. This method accepts the database URL (an address that points to your database), Username and, password as parameters and, returns a connection object.

Invoke this method by passing, the URL of the desired database, user name and, password as parameters to it.

String url = "jdbc:mysql://localhost/";
String user = "root";
String passwd = "password";
Connection conn = DriverManager.getConnection(url, root, passwd);

Example

Following is an example JDBC program which establishes a connection with a database.

import java.sql.*;
public class JDBCExample {
   //JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/";
   //Database credentials
   static final String USER = "root";
   static final String PASS = "password";

   public static void main(String[] args) {
      Connection conn = null;
      try{
         //STEP 2: Register JDBC driver
         Class.forName("com.mysql.jdbc.Driver");
         //STEP 3: Open a connection
         System.out.println("Connecting to database...");
         conn = DriverManager.getConnection(DB_URL, USER, PASS);
         System.out.println("Connection established");
         } catch(Exception e) {
      }
      System.out.println("Goodbye!");
   }
}

Output

Connecting to database...
Connection established
Goodbye!

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements