(Translated by https://www.hiragana.jp/)
JDBC Tutorial - GeeksforGeeks
Open In App

JDBC Tutorial

Last Updated : 20 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JDBC stands for Java Database Connectivity. JDBC is a Java API or tool used in Java applications to interact with the database. It is a specification from Sun Microsystems that provides APIs for Java applications to communicate with different databases. Interfaces and Classes for JDBC API comes under java.sql package. In this Java JDBC tutorial, we will be learning about what is Java Database Connectivity with suitable example.

In the present world, where we mostly deal with websites and databases it is as if they matter the most but if we closely look over it is data that matters the most. If we look closer that all developers are revolving and working over the web and mobile technologies but what remains the same is the data.

JDBC-Tutorial

Hence, there is an urgency to figure out how data is being handled for which this concept comes into play.

coreJava_concepts

Let us do have an overview of why do we need this term which can be better interpreted with the image provided below.

Why do we need to learn advanced java?

As we are well versed with all the concepts of Core Java now comes the time to build projects that will results out in building an application as a final product.  So if we do are only aware of core java we can only build applications that can be run on the machine where the components of it are stored(in simpler words one can say where all the codes are written). These types of applications are known as standalone applications.

coreJava_application

Note: Standalone applications being one of two types of applications in the programming world only holds for 5% of the applications in the real world.  

Hence, the scope is very constricted if we only do build standalone applications resulting out in the very little scope of development and scalability which gives birth to advance java which in turn gives birth to 3 components primarily namely JSP, Servlets, and JDBC in order to make the applications run on multiple machines. With the evolution of these 3 components, it removes the constraint of running only a single machine as it was impractical to users in the real-world application is made but forcing users to install then use them. Now, these types of applications are known as web applications that are the applications providing the services to the end-users without installing them. These applications are known as web applications which are not standalone applications.

Now you must be wondering what is JSP and Servlet and how JDBC is interrelated with them. For the time being, just focus only on JDBC in order to get started with what exactly it is and how to use it by referring to the image depicted below as follows:

getStartedWithJDBC_flow_diagram

Note: Conclusion drawn from Image is as follows:

  • JSP stands for Java Server Pages where these pages are considered as View Components as Presentation logic.
  • Servlet is meant for internal processing going on such as reading, fetching values from the database, comparison, etc in the backend as Processing Logic in our process servlet. Servlets do also contain java classes for this background processing for processing logic.
  • JDBC is meant for Connectivity of Java Application in servlets as discussed to our Database.

What is JDBC?

Let us try to discuss this from scratch till now in the java domain we were simply writing codes(programming) and interacting with the database. Have you ever wonder imagining how internally our program can be linked to a database giving it enormous power to make projects and applications out of our program. Yes, it is possible with the help of this mechanism. Let us discuss in a real-world scenario which later on we will be mapping with technical terms to get an absolute technical understanding of the same with a pictorial representation.

JDBC_connectivity

Real-world example:

Consider two places A and B. Now people residing on A do not know the language of people residing on place B and vice-versa which we will be going to map with technical terms to discuss out major components inside the JDBC.

real_world_example_diagram

Mapping the same with technological terms to illustrate above real illustration. Here place A is referred to as a java application and place B is therefore referred to as a database. Now the translator as discussed above which is responsible for converting java application calls to database calls and database calls to java application calls is nothing but a ‘Driver Software’. The road between applications is ‘Connection’ and lastly the vehicle is our ‘statement object’.  Now ‘requirement’ above is our SQL query and the ‘small block’ generated after processing the SQL statement by the database engine has been passed in nothing but ‘ResultSet’. Now, this technology by which java applications is communicating with database is ‘Java Database Connectivity. By now we are done with a crystal clear overview of JDBC and geek you will be surprised that we already have covered it, let dig down to get to know the working of components which will be described up to greater depth in the environment setup of JDBC. 

Now we will penetrate down into the JDBC component which as discussed above is a technology that is used to connect Java applications with the database. It is an API consisting of lots of classes and interfaces by which with the help of some classes and interfaces we are able to connect the java application to the database as pictorially depicted above. It has mainly two packages namely as follows: java.sql package and javax.sql package.

Note: For reference above SQL is taken as database to illustrate packages names.  

typesOfJDBC_APIs

Interfaces and Classes of JDBC API

Some popular interfaces of JDBC API are listed below:

  • Driver interface
  • Connection interface
  • Statement interface
  • PreparedStatement interface
  • CallableStatement interface
  • ResultSet interface
  • ResultSetMetaData interface
  • DatabaseMetaData interface
  • RowSet interface

Some important Classes of JDBC API are listed below:

  • DriverManager class
  • Blob class
  • Clob class
  • Types class

So here is how we are going to cover JDBC ailments in order to get how technically the whole process revolves.

  • What is JDBC
  • Need of JDBC
  • JDBC Architecture
  • JDBC Environment Setup
  • Steps to connect JDBC
  • JDBC example as implementation

JDBC Architecture 

JDBC_architecture

To know in-depth about the above diagram, you can refer this article Architecture of JDBC .

JDBC Environment Setup

Now let us do discuss out various types of drivers in JDBC. So basically there are 4 types of standard drivers listed below:

Now, you must be wondering about they are their point do come out which drivers to be used. The solution to this is as simple as we need to use the driver as per accordance with the database with which we are interacting. 

Note: Drivers to be used are directly propionate to which kind of database with which we are dealing.

Drivers are mentioned in the tabular format below corresponding to the database which is as follows:

Database Driver name 
MySQL com.mysql.jdbc.Driver

Now you must be wondering out from where these listed drivers are to be imported. So in order to import the drivers, you need to download a JAR file from the web. Considering the most frequently used database namely MySQL you need to download a JAR file named ‘mysql.connector‘ and so on it goes for other databases.

Note: It is not an essential step as different IDE’s possesses different traits. In some IDE these connectors are inbuilt such as NetBeans while in Eclipse you need to import this JAR file as discussed above by simply downloading corresponding JAR file from the internet and load in the project. 

If you do not know how to import JAR files to libraries in java IDE, first go through this step.

JDBC_environment_setup

Steps to connect JDBC

There are basically seven steps to get your java application connected to deal with the database. Here database could be structured or non-structured, we have to deal accordingly for the same which will be clear by the end of sequential steps execution. In generic mostly we deal with either MySQL or Oracle database as far it is concerned for our java application. Here we will be dealing out with the MySQL database for our java application wherein processing we just have to execute these listed steps below in sequential order to connect JDBC which is as follows:

  1. Import the required package for the corresponding database.
  2. Load and register the JDBC drivers.
    • First load then register the same
  3. Establish the connection
  4. Create a statement
  5. Execute the query
  6. Process the results
  7. Close the connections

Let us discuss the above steps by picking up cases from the real world to get a clear sake of understanding our concept. Considering an illustration of mobile networking which is as follows: 

Real-life implementation of JDBC is most frequently seen in mobile networking which is illustrated as follows:

  • Consider you want to talk to somebody far away. For which one needs a device known as cell-phone/telecom which signifies our Step 1.
  • Now user needs a network and a SIM card which is equivalent to the loading and registering process signifying Step 2.
  • Now with a working SIM card, physical labor is required to dial numbers and pressing the call button signifying step 3 as we are trying to establish the connection to commute.
  • Whatever message we need to deliver is equivalent to creating a statement.
  • Now once connected we need to speak the message as we have thought off, which is equivalent to the execution of the query.
  • Now a response will be received which was our goal signifies step 6 of processing results technically in the case of JDBC.
  • Lastly, we need to press the button on the device to close communication, similarly, it is a good practice of closing the connections in the technical aspect which here is JDBC.

Implementation (Working of JDBC)

  • Suppose the database with which we want to deal is MySQL. So first we need to import the package, for SQL database it is namely ‘java.sql.*‘.
  • Now as per IDE(we need to load its corresponding JAR file in our project in IDE where JAR is manually supposed to be inserted in the IDE, taking ‘eclipse IDE‘ for reference as an IDE in order to illustrate the same in the below example.
  • By far we are done with importing the JAR to our project. Now in order to load the driver, we will be using forName() method by writing “com.mysql.driver_name” which belongs to class ‘class

Syntax:

class com.mysql.jdbc.Driver ;
  • Now in order to establish the connection, we have to instantiate an interface named ‘Connection’
  • Now statements are of three types:
    1. Normal statements:
    2. Prepared statements:
    3. Callable statements: Stored procedures
  • Once the statement is created, now we will be executing the query in our database as per the perceived response from the database. Suppose if we want to fetch data from the database then the response is table structure here or if we are simply inserting the values then response if the number of rows effectively.
  • Lastly, whatever we are getting either a table or simply rows, now we simply need to process the results.
  • Also, it is recommended to good practice by closing the connections to release and free up memory resources by closing the object of interface and statement objects.

Illustration: Setting up JDBC

Java




// Java Program to Illustrate Setting Up of JDBC
 
// Importing SQL database
import java.sql.*;
 
// Main class to illustrate demo of JDBC
class GFG {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
 
        // Loading and registering drivers
        // Optional from JDBC version 4.0
        Class.forName("oracle.jdbc.OracleDriver");
 
        // Step 2:Establishing a connection
        Connection con = DriverManager(
            "jdbc:oracle:thin:@localhost:1521:XE",
            "username", "password");
 
        // Step 3: Creating statement
        Statement st = con.createStatement();
 
        // Step 4: Executing the query and storing the
        // result
        ResultSet rs = st.executeQuery(
            "select * from Students where Marks >= 70");
 
        // Step 5: Processing the results
        while (rs.next()) {
            System.out.println(rs.getString("students"));
            System.out.println(rs.getInt("marks"));
        }
 
        // Step 6: Closing the connections
        // using close() method to release memory resources  
        con.close();
       
      // Display message for successful execution of program
      System.out.println("Steps in Setting Up of JDBC");
    }
}


Output

Steps in Setting Up of JDBC

Now let us move ahead and discuss its interaction with the real database after successfully setting up with the database how internally things are getting managed. Here we will be having to create two classes, one is our connection class and the other one where we will be implementing in application.java class using the connector object. We are done with the connection class in the above illustration, so let us now finally discuss the application class with help of an example. Considering the database ‘MySQL here to interpret and code out the same.

Implementation: Query in our MySQL database is as follows:

select * from Student;
insert into Students values(7, geeksforGeeks);
select username from Student where userid = 7;

Example:

Java




// Java Program to Illustrate Working Of JDBC
// with Above Query in Database
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
// JDBC demo class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declaring and initializing arguments that
        // needed to be passed later in getConnection()
        String url = "jdbc:mysql://localhost/test";
        String uname = "root";
        String pass = "";
 
        // Query from the database taken
        // Custom query taken to illustrate
        String query
            = "select username from Student where id=7";
 
        // Loading and registering drivers
        Class.forName("com.mysqljdbc.Driver");
 
        // Creating an connection object by
        // getConnection() method which is static method and
        // returns the instance of Connection class
 
        // This method takes 3 parameters as defined above
        Connection con
            = DriverManager.getConnection(url, uname, pass);
 
        Statement st = con.createStatement();
 
        // It returns a tabular structure so we need
        // ResultSet as it stores chunk of data into
        // structures
        ResultSet rs = st.executeQuery(query);
 
        // Now we are having our data in object of ResultSet
        // which is no more tabular
 
        // Note:
        // Fetching the above data by storing it as a String
        // Here pointer is lagging with data for which we
        // use next() method to
        // take it to next record
        rs.next();
 
        // Here we are fetching username column data
        String name = rs.getString("username");
 
        // Lastly print the data
        System.out.println(name);
 
        // It is  good practice to close the connection
        // using close() method
 
        // Closing the statement first
        st.close();
       
        // Now close the connection also
        con.close();
    }
}


Output

GeeksforGeeks


Previous Article
Next Article

Similar Reads

Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
How to Commit a Query in JDBC?
COMMIT command is used to permanently save any transaction into the database. It is used to end your current transaction and make permanent all changes performed in the transaction. A transaction is a sequence of SQL statements that Oracle Database treats as a single unit. This statement also erases all save points in the transaction and releases t
5 min read
Simplifying CRUD Operation with JDBC
Creating, reading, updating, and deleting data in a database is a common task in many applications, and JDBC (Java Database Connectivity) is a Java API that allows you to connect to a database and perform these operations. In this blog post, we will walk through the steps of setting up a simple CRUD (create, read, update, delete) operation using JD
3 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let's understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate. Before getting into the difference
2 min read
How to Insert Records to a Table using JDBC Connection?
Before inserting contents in a table we need to connect our java application to our database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides the applications-to-JDBC connection and JDBC driver provid
4 min read
Java Program to Retrieve Contents of a Table Using JDBC connection
It can be of two types namely structural and non-structural database. The structural database is the one which can be stored in row and columns. A nonstructural database can not be stored in form of rows and columns for which new concepts are introduced which would not be discussing here. Most of the real-world data is non-structural like photos, v
5 min read
Delete Contents From Table Using JDBC
JDBC(Java Database Connectivity) is a standard API(application interface) between the java programming language and various databases like Oracle, SQL, PostgreSQL, etc. It connects the front end(for interacting with the users) with the backend(for storing data). Approach: 1. CREATE DATABASE: Create a database using sqlyog and create some tables in
2 min read
How to Execute Multiple SQL Commands on a Database Simultaneously in JDBC?
Java Database Connectivity also is known as JDBC is an application programming interface in Java that is used to establish connectivity between a Java application and database. JDBC commands can be used to perform SQL operations from the Java application. Demonstrating execution of multiple SQL commands on a database simultaneously using the addBat
6 min read
JDBC - Type 4 Driver
Let us do get a cover overview of the JDBC and the ODBC prior in order to better understand what exactly is type 4 driver. A JDBC driver enables Java application to interact with a database from where we can fetch or store data. JDBC drivers are analogous to ODBC drivers. The JDBC classes are contained in the Java Package java.sql and javax.sql.JDB
3 min read
JDBC - Type 2 Driver
A JDBC driver enables Java application to interact with a database from where we can fetch or store data. JDBC drivers are analogous to ODBC drivers. The JDBC classes are contained in the Java Package java.sql and javax.sql.JDBC helps to Connect to a data source, like a database.Send queries and update statements to the databaseRetrieve and process
2 min read
JDBC - Type 1 Driver
A JDBC driver enables Java application to interact with a database from where we can fetch or store data. JDBC drivers are analogous to ODBC drivers. The JDBC classes are contained in the Java Package java.sql and javax.sql.JDBC helps to Connect to a data source, like a database.Send queries and update statements to the databaseRetrieve and process
3 min read
JDBC - Type 3 Driver
A JDBC driver enables Java application to interact with a database from where we can fetch or store data. JDBC drivers are analogous to ODBC drivers. The JDBC classes are contained in the Java Package java.sql and javax.sql.JDBC helps to Connect to a data source, like a database.Send queries and update statements to the databaseRetrieve and process
2 min read
Inserting Records in Batch Using JDBC
It is carried out using the functions namely addBatch() and executeBatch() methods. For that lets us do have a prior understanding of JDBC drivers. So, in order to connect to your database in Java, you need a JDBC driver. Every database (MySQL, Oracle, etc.) comes with its own JDBC driver, usually built by the database vendor and found on the datab
2 min read
Spring - Prepared Statement JDBC Template
In Enterprise applications, data access/stored in relational databases is a common requirement. As an essential part of Java SE, Java Database Connectivity (JDBC) defines a set of standard APIs to access relational databases in a vendor-independent fashion. However, when using JDBC, the developer has to manage all database-related resources and han
5 min read
Java JDBC - Difference Between Row Set and Result Set
ResultSet characteristics are as follows: It maintains a connection to a database and because of that, it can’t be serialized.it can not pass the Result set object from one class to another class across the network.ResultSet object maintains a cursor pointing to its current row of data. Initially, the cursor is positioned before the first row. The
2 min read
Difference Between Connected vs Disconnected RowSet in Java JDBC
A RowSet is a wrapper around a ResultSet object. It can be connected, disconnected from the database, and can be serialized. It maintains a JavaBean component by setting the properties. You can pass a RowSet object over the network. By default, the RowSet object is scrollable and updatable. This diagram will give you more idea about ResultSet and R
5 min read
Servlet With JDBC
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. Properties of Servlets are as follows: Servlets work on the server-side.Servlets are capable of handling
12 min read
Hibernate - Difference Between ORM and JDBC
Hibernate is a framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic that is independent of database software. ORM (Object-Relational Mapping) ORM, an abbreviation for Ob
4 min read
Spring JDBC Example
JDBC or Java Database Connectivity is a specification from Sun microsystems that provides a standard abstraction(that is API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standards. It is used to write programs required to access databases. JDBC along with the data
4 min read
Advantages of Spring Boot JDBC
Spring JDBC is used to build the Data Access Layer of enterprise applications, it enables developers to connect to the database and write SQL queries and update data to the relational database. The code related to the database has to be placed in DAO classes. SpringJDBC provides a class called JdbcTemplate to handle the database-related logic. Jdbc
3 min read
Spring - Using SQL Scripts with Spring JDBC + JPA + HSQLDB
We will be running the SQL scripts with Spring JDBC +JPA + HSQLDB. These scripts are used to perform SQL commands at the time of application start. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. JPA is just a specification that faci
3 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
JUnit - Sample Maven Project With JDBC
The quality of software should be of a high standard and then only it is liked and used by most people. A good programmer is one who prepares software error-free, JUnit helps us a lot in achieving that. In this article, let us see a MySQL database connecting with Java via JDBC, and the data is checked against JUnit. Example Maven Project Project St
6 min read
How to Call Stored Functions and Stored Procedures using JDBC?
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun microsystems that provides a standard abstraction(API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standards. It is used to write pr
5 min read
Standard Steps to Be Followed For Developing JDBC Application
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun microsystems that provides a standard abstraction(API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standards. It is used to write pr
4 min read
Working with Large Objects Using JDBC in Java
Sometimes as part of programming requirements, we have to insert and retrieve large files like images, video files, audio files, resumes, etc with respect to the database. Example: Uploading images on the matrimonial websiteUpload resume on job-related websites To store and retrieve large information we should go for Large Objects(LOBs). There are
5 min read
Spring Security - JDBC Authentication
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun Microsystems that provides a standard abstraction(API or Protocol) for Java applications to communicate with various databases. It provides the language with Java database connectivity standards. It is used to write pr
8 min read
Spring Data JDBC Extensions
In this article, We will explore the realm of Spring Data JDBC extensions. Discover how they enhance the functionalities of the Spring Data JDBC module. These extensions offer a range of tools that enable developers to handle database interactions, with skill-making tasks, like simplifying queries enhancing security, and optimizing performance mana
3 min read
Spring - JDBC Template
In this article, we will discuss about Spring JDBC Template and how to configure the JDBC Template to execute queries. Spring JDBC Template provides a fluent API that improves code simplicity and readability and the JDBC Template is used to connect to the database and execute SQL Queries. JDBC (Java Database Connectivity) is an application programm
5 min read
Difference between ODBC and JDBC
JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity). These both are API standards used for connecting applications to databases. ODBC can be used by various programming languages as it is a general API standard. But JDBC is Java-specific and it provides a Java-based interface for database access. ODBC drivers are not Java-centri
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg