Table of contents
1.
Introduction
2.
What is JDBC?
3.
Necessity of JDBC
4.
Establishing Connection in JDBC
4.1.
1. First of all, we do need to Import the database. 
4.2.
2. Then we have to load the driver using the forName () method. 
4.3.
3. Now, we have to register the driver in DriverManager. 
4.4.
4. Next, form a Connection using a Connection class object 
4.5.
5. We now need to create a statement. 
4.6.
6. Execution of the query 
4.7.
7. Closing the connection
5.
Implementation
6.
Frequently Asked Questions
6.1.
What are the main steps in Java to establish JDBC Connection?
6.2.
What are the different types of JDBC statements?
7.
Conclusion
Last Updated: Aug 10, 2024
Medium

JDBC Connection in Java

Author Vivek Goswami
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

It is often a necessity for our program to interact with a database and produce suitable query output as per our needs. Many methods help us obtain such results, one of them being JDBC. JDBC provides users with different types of functionality. The JDBC connection is one of the essential features that JDBC provides. We use a JDBC connection to establish a connection with the database. In other words, it's an API. 

JDBC Connection in Java

After successfully connecting it to the Database, you can perform different operations on the database, depending on your user requirements, such as Insert, delete, update, etc. To connect to the database, you need to consider various parameters such as JDBC packages, JDBC drivers, URL creation, and connection objects. 

So, we have gone through a basic description of a JDBC Connection. Let us dive into the details of the topic now.

What is JDBC?

JDBC is an abbreviation for Java Database Connectivity. It is a Java API for connecting to a database and executing queries. Let us now understand what an API is. An API (Application Programming Interface) is a document that contains a description of all the features of a product or software. It represents the classes and interfaces that software programs can follow to communicate with each other. We can create APIs for applications, libraries, operating systems, etc.

JDBC is a part of the Java SE (Java Standard Edition). The JDBC API uses the JDBC driver to connect to the database. There are four types of JDBC drivers: 

  1. JDBCODBC bridge driver
  2. Local driver 
  3. With network protocol driver 
  4. Thin driver

These drivers help us in establishing the JDBC Connection.

Also see, Hashcode Method in Java

Necessity of JDBC

JDBC is an evolution of ODBC, which is platform-dependent and has many drawbacks. The ODBC API is written in C, C ++, Python, and core Java, platform-dependent languages. Therefore, the development of JDBC was by a database provider consisting of classes and interfaces written in Java to eliminate dependencies.

Establishing Connection in JDBC

To establish the JDBC Connection, we need to follow a specific process. Let us now understand what that process is by going through the steps involved in it one by one:

1. First of all, we do need to Import the database. 

2. Then we have to load the driver using the forName () method. 

You must first load or register the driver before using it in your program. We need to load the driver before using it in our program. We can register the driver in one of two ways: 

i. Class.forName ():
This method loads the driver class files into memory during the run time. You don't have to use new objects or create objects. In the following example uses Class.forName () to load the Oracle driver as  follows:
The syntax for this is Syntax: Class.forName(“oracle.jdbc.driver.OracleDriver”)

ii.  DriverManager.registerDriver () 

DriverManager is a Java built-in class with static member registers. Here, we have called the constructor of the driver class at the compile time. In the following example uses DriverManager.registerDriver () to register the Oracle driver. Let us have a look at it.

Syntax: DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())

3. Now, we have to register the driver in DriverManager. 

4. Next, form a Connection using a Connection class object 

After loading the driver, we can establish a connection in the following ways

Connection con = DriverManager.getConnection(url,user,password)

It requires the following parameters:

  1. user: The user name that can access the SQL prompt. 
  2. Password: The password you can use to access the SQL prompt.
  3. Con: This is a reference to the connection interface. 
  4. URL: Uniform Resource Locator  

We have looked at all the parameters required to maintain the connection. Let us see an example to understand it better:

Example :

String url = “ jdbc:oracle:thin:@localhost:5421:xe”

5. We now need to create a statement. 

Since we have established the connection, we can work with the database. The CallableStatement, JDBCStatement and PreparedStatement interfaces define the methods we can use to send SQL commands and receive data from the database. The usage of the  JDBC statement is as follows:

Statement st = con.createStatement();

6. Execution of the query 

The query here is a SQL query. Now you know that you can execute multiple types of queries, like queries to update/insert a table in the database. A query to get the data. We use the executeQuery () method of the Statement interface to execute a query to get a value from the database. This method returns an object in the  ResultSet. We can use the ResultSet object to extract the records from the table. We use the executeUpdate (SQL query) method to execute update/insert queries.

7. Closing the connection

In the end, we have sent the data to the specified location and are nearing the task's completion. When you close the connection, the Statement and ResultSet objects close automatically. We use the close () method of the Connection interface to close the connection. 

It will be as follows: 

con.close ();

Implementation

// A Java Program for Establishing Connection in JDBC

// Importing the database
import java.sql.*;
// Importing the required classes
import java.util.*;

// Main class of Java
class Main
{

    // The Main driver method
public
    static void main(String a[])
    {

        // Creating a connection using Oracle DB
        String url = "jdbc:oracle:thin:@localhost:5241:xe";

        // Username and password to access DB
        // Custom initialization
        String user = "superuser";
        String pass = "54321";

        // Entering data
        Scanner k = new Scanner(System.in);

        System.out.println("enter employee_name");
        String employee_name = k.next();

        System.out.println("enter employee_id");
        int employee_id = k.nextInt();

        System.out.println("enter department");
        String department = k.next();

        // Inserting data using SQL query
        String sql = "insert into employee1 values('" + employee_name + "'," + employee_id + ",'" + department + "')";

        // Connection class object
        Connection connectionn = null;

        // Try block to check for exceptions
        try
        {

            // Registering drivers
            DriverManager.registerDriver(
                new oracle.jdbc.OracleDriver());

            // Reference to connection interface
            connectionn = DriverManager.getConnection(url, user,
                                                      pass);

            // Creating a statement
            Statement st = connectionn.createStatement();

            // Executing query
            int m = st.executeUpdate(sql);
            if (m == 1)
                System.out.println(
                    "inserted successfully : " + sql);
            else
                System.out.println("insertion failed");

            // Closing the connections
            connectionn.close();
        }

        // Catch block to handle exceptions
        catch (Exception ex)
        {
            // Display message when exceptions occurs
            System.err.println(ex);
        }
    }
}

 

Output:

Enter employee_name
Ninja
Enter employee_id
6523
Enter department
12A
inserted successfully:  insert into employee1 values(‘Ninja',6523, '12A')


Practice by yourself on java online compiler.

Frequently Asked Questions

What are the main steps in Java to establish JDBC Connection?

The main steps are as follows:
a. Load the driver.
b. Make the Connection
c. Get the object of statement
d. Execution of query
e. Close the connection

What are the different types of JDBC statements?

There are basically three types of JDBC statements:
a. Statement 
b. PreparedStatement
c. CallableStatement

Conclusion

JDBC (Java Database Connectivity) is a crucial API for connecting and executing queries with databases in Java. It simplifies database interactions, supports a variety of database systems, and enables seamless integration of database operations into Java applications. JDBC enhances data handling capabilities, promotes code portability, and is essential for building robust, data-driven applications. Proper management of JDBC resources ensures efficient and reliable database access.
Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass