×

Advanced Coding & Software Engineering Program

Duration: 1 Year (12 Months)

Join our premium 1-year program to master cutting-edge technologies and become an industry-ready Software Engineer!

Course Coverage

  • Languages: C, C++, Java, JavaScript, Python
  • Web Technologies: HTML, CSS, Bootstrap 5, MERN Stack, Full Stack Development
  • Databases: MySQL, MongoDB
  • Data Science Libraries: Pandas, NumPy
  • Development Tools: Visual Studio Code, IntelliJ IDEA, PyCharm, Postman, Git, GitHub
  • Cloud Platforms: Vercel, MongoDB Atlas

Program Highlights

  • Live Classes: Interactive sessions with real-time doubt resolution
  • Hands-On Sessions: Practical coding exercises to build real-world skills
  • Industry Experts: Learn from professionals with years of experience
  • Live Project: Work on real-world projects to apply your skills
  • Get Certificate: Earn a professional certificate upon program completion

Course Fee: Only ₹1020 / month
Limited Period Offer!

JDBC in Java – Complete Tutorial (Beginner to Advanced)



Last Updated on: 27th Nov 2025 15:56:01 PM

Modern applications interact with databases all the time—login validation, signup, transactions, orders, payments, attendance systems, todo apps, banking software, and more. To connect Java applications with databases like MySQL, Oracle, PostgreSQL, SQL Server, Java provides a powerful API called JDBC (Java Database Connectivity).

 

JDBC acts as a bridge between Java programs and database software.

 

Without JDBC, Java cannot communicate with a database.

 

In real life, JDBC works just like:

  • A phone dialer connecting your phone (Java application) to another phone (database).

  • A POS machine connecting a shop’s system (Java app) with the bank server (database).

  • A food delivery app connecting customer actions to backend order databases.

 

JDBC provides a standard way to:

✔ Connect to a database
✔ Send SQL queries
✔ Retrieve data
✔ Insert, update, delete records
✔ Process results
✔ Close the connection safely

This tutorial explains everything about JDBC from basics to advanced usage.

 

What is JDBC?

JDBC (Java Database Connectivity) is an API in Java used to connect and execute queries with databases.

JDBC is a part of Java Standard Edition (JSE).

 

Why Use JDBC?

  • To store data permanently

  • To read and modify database records

  • To build database-based applications

  • To interact with relational databases

  • To perform CRUD operations (Create, Read, Update, Delete)

 

JDBC Architecture

JDBC architecture follows two-tier / three-tier model:

Java Application → JDBC API → JDBC Driver → Database

 

  • Java Application: Your code

  • JDBC API: Classes & interfaces

  • JDBC Driver: Vendor-specific implementation

  • Database: MySQL / Oracle / etc.

 

Important JDBC Interfaces (Very Important for Interviews)

 

1️⃣ DriverManager

Manages database drivers and opens connections.

2️⃣ Connection

Represents a connection between Java and the database.

3️⃣ Statement

Used for executing static SQL queries (not recommended for user input).

4️⃣ PreparedStatement

Used for dynamic, secure SQL queries (recommended).
✔ Prevents SQL Injection

5️⃣ CallableStatement

Used for calling stored procedures.

6️⃣ ResultSet

Used to store and process data returned from SELECT queries.

 

JDBC Driver Types

Type Description Most Used?
Type 1 JDBC-ODBC Bridge ❌ Old, not used
Type 2 Native API Driver ❌ Rare
Type 3 Network Protocol Driver ❌ Rare
Type 4 Pure Java Driver ✔ Most commonly used (MySQL, Oracle, etc.)

 

Real-Life Example: JDBC

 

Scenario: Login System

When a user enters email + password:

  1. Java reads input

  2. JDBC sends query to database:  

SELECT * FROM users WHERE email=? AND password=?
  1. ResultSet checks if data exists

  2. Java decides login success or failure

 

This is how WhatsApp, Swiggy, Zomato, bank apps work internally.

 

JDBC Steps (Very Important)

JDBC works in 6 steps:

1️⃣ Load Driver
2️⃣ Create Connection
3️⃣ Create Statement / PreparedStatement
4️⃣ Execute Query
5️⃣ Process Result
6️⃣ Close Connection

 

JDBC Program: Connect to MySQL (Step-by-Step)

Step 1 – Download MySQL JDBC Driver

File: mysql-connector-j.jar
(Place it in your project → Add to Library)

 

Step 2 – Create Database & Table

CREATE DATABASE studentdb;

USE studentdb;

CREATE TABLE students (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    email VARCHAR(50)
);

 

Step 3 – JDBC Code (Insert Data)

import java.sql.*;

public class InsertData {
    public static void main(String[] args) {
        try {

            // 1. Load Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. Create Connection
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/studentdb",
                "root",
                "your_password"
            );

            // 3. Create PreparedStatement
            String sql = "INSERT INTO students (name, email) VALUES (?, ?)";
            PreparedStatement ps = con.prepareStatement(sql);

            ps.setString(1, "Rahul");
            ps.setString(2, "rahul@gmail.com");

            // 4. Execute
            ps.executeUpdate();

            System.out.println("Record Inserted Successfully!");

            // 5. Close Connection
            con.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

SELECT Example (Fetch Data)

import java.sql.*;

public class FetchData {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/studentdb",
                "root",
                "your_password"
            );

            String sql = "SELECT * FROM students";
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(sql);

            while (rs.next()) {
                System.out.println(
                    rs.getInt(1) + " | " +
                    rs.getString(2) + " | " +
                    rs.getString(3)
                );
            }

            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

UPDATE Example

String sql = "UPDATE students SET name=? WHERE id=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "Amit");
ps.setInt(2, 2);
ps.executeUpdate();

 

DELETE Example

String sql = "DELETE FROM students WHERE id=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 3);
ps.executeUpdate();

 

Security: Why Use PreparedStatement?

  • Prevents SQL Injection

  • Faster than Statement

  • Supports dynamic parameters

  • Used in real-world apps

 

Real Life Example: E-Commerce Orders

When you place an order:

INSERT INTO orders (user_id, product_id, amount) VALUES (?, ?, ?)

 

Java sends this using JDBC.

Every payment system, delivery app, hospital management system uses JDBC internally.

 

Common JDBC Errors (With Meaning)

Error Meaning
Communications Link Failure Wrong MySQL URL/port
Access Denied Wrong username/password
ClassNotFoundException Driver JAR missing
SQLSyntaxErrorException Wrong SQL query

 

Summary

  • JDBC connects Java with databases

  • Uses DriverManager, Connection, Statement, ResultSet

  • Supports CRUD operations

  • PreparedStatement is secure

  • Used in all real-world applications

 

Keep coding — you're ready for real-world Java development!

Happy Learning!  yes

 


Online - Chat Now
Let’s Connect

Inquiry Sent!

Your message has been successfully sent. We'll get back to you soon!

iKeySkills Logo