Java Database Connectivity Steps (JDBC Steps)

This tutorial describe about the steps require for database connectivity in java. You have to follow the steps one by one in order to connect the database.

We will use the type 4 driver in these steps to connect the database. Here we go

Step1: Registering the database driver

First you have to know that which database you are using in your application. There can be any database like Mysql, Oracle etc.

In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver.

The return type of the Class.forName (String className) method is Class. Class is a class in java.lang package.

try {
    Class.forName("com.mysql.jdbc.Driver"); // Or any other driver which database you want to connect.
} catch (ClassNotFoundException ex) {
    ex.printStackTrace();
}

Step2: Creating a Mysql jdbc Connection

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. The getConnection() method get a connection from database. It uses a username, password, and a jdbc URL to establish a connection to the database and returns a connection object.

A jdbc Connection represents a connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions.

For MYSQL database it would be like: jdbc:mysql://localhost/databasename

In the above MYSQL URL it has the different meaning for different term used.

Jdbc –> protocol.

Mysql –> sub protocol.

Localhost –> server URL where the database exists.

Databasename –> database name to want to connect.

Below code is showing how to get the MYSQL Connection from database.

try {
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/databasename", "username", "password");
} catch (SQLException e) {
    e.printStackTrace();
}

Step3. Get a jdbc Statement object

After getting the database Connection object, we have to get the Statement object to run the SQL query on database and get the result. You can get the Statement object from your connection object by using the createStatement() method.

try {
    Statement statement = connection.createStatement();
} catch (SQLException e) {
    e.printStackTrace();
}

The Statement object is used to send and execute SQL queries to a database.

There are three types of JDBC Statement object; we will discuss each in separate tutorials.

Step4. Finally execute the SQL query and get the Resutlset

After getting the statement object, your SQL query is ready to run on database. The Statement object has methods that are used to execute the SQL query on connected database.

Mainly the statement object has three methods to executing SQL query.

executeQuery(): This method used to execute the SELECT SQL query on database.

executeUpdate(): This method used to execute the INSERT, UPDATE or DELETE, actually this method used to execute the SQL query which does not return anything.

execute(): This method executes the given SQL statement, which may return multiple results. In some situations, a single SQL statement may return multiple result sets and/or update counts. Normally you can ignore this unless you are executing a stored procedure that you know may return multiple results or you are dynamically executing an unknown SQL string.

Resutlset Object: The Resutlset provides access to a table of data return by executing a Statement. The table rows are retrieved in sequence. The ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results.

The below example show you all the steps to connect to MYSQL database.

package com.java.connect.jdbc;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class JDBCDatabaseStepsExample {
 
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
 
        try {
            // Step1:Register the mysql driver
            Class.forName("com.mysql.jdbc.Driver"); // Or any other driver which database you want to connect.
            // Step2:Get the connection object
            connection = DriverManager.getConnection("jdbc:mysql://localhost/databasename", "username", "password");
            // Step3:Get the statement object
            statement = connection.createStatement();
            // Prepare the SQL query
            String SQL = "SELECT NAME, AGE FROM PERSON";
            // Step4: Run the SQL query and get the ResultSet object.
            resultSet = statement.executeQuery(SQL);
            // Retrive the data from ResultSet
            while (resultSet.next()) {
                System.out.println("The name of person is : " + resultSet.getString(1));
                System.out.println("The age of person is : " + resultSet.getString(2));
            }
 
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // Finally we have close all the JDBC resources
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}