Skip to main content
Java Basics
CHAPTER 24 Beginner

Java JDBC and Database Connectivity

Updated: May 17, 2026
5 min read

# CHAPTER 24

Java JDBC and Database Connectivity

1. Introduction

JDBC (Java Database Connectivity) is Java's API for connecting to and interacting with relational databases like MySQL, PostgreSQL, and Oracle. It's the bridge between your Java application and the database.

2. JDBC Architecture

1
Java Application → JDBC API → JDBC Driver → Database (MySQL)

3. Setting Up MySQL Connection

java
123456789101112131415
import java.sql.*;

public class DatabaseDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/school_db";
        String user = "root";
        String password = "";

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            System.out.println("Connected to MySQL successfully!");
        } catch (SQLException e) {
            System.out.println("Connection failed: " + e.getMessage());
        }
    }
}

4. CRUD Operations

CREATE (Insert):

java
12345678
String sql = "INSERT INTO students (name, age, grade) VALUES (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
    pstmt.setString(1, "Alice");
    pstmt.setInt(2, 20);
    pstmt.setString(3, "A");
    int rows = pstmt.executeUpdate();
    System.out.println(rows + " row(s) inserted.");
}

READ (Select):

java
123456789
String sql = "SELECT * FROM students";
try (Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery(sql)) {
    while (rs.next()) {
        System.out.printf("ID: %d, Name: %s, Age: %d, Grade: %s%n",
            rs.getInt("id"), rs.getString("name"),
            rs.getInt("age"), rs.getString("grade"));
    }
}

UPDATE:

java
123456
String sql = "UPDATE students SET grade = ? WHERE name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
    pstmt.setString(1, "A+");
    pstmt.setString(2, "Alice");
    pstmt.executeUpdate();
}

DELETE:

java
12345
String sql = "DELETE FROM students WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
    pstmt.setInt(1, 5);
    pstmt.executeUpdate();
}

5. PreparedStatement vs Statement

FeatureStatementPreparedStatement
SQL InjectionVulnerableProtected
PerformanceSlower (re-parsed)Faster (pre-compiled)
ParametersConcatenationPlaceholders ?

Always use PreparedStatement in production code!

6. Mini Project: Student Database Application

java
1234567891011121314151617181920212223242526272829303132333435363738394041424344
import java.sql.*;
import java.util.Scanner;

public class StudentDB {
    static final String URL = "jdbc:mysql://localhost:3306/school_db";

    public static void main(String[] args) throws SQLException {
        Connection conn = DriverManager.getConnection(URL, "root", "");
        Scanner sc = new Scanner(System.in);

        System.out.println("=== STUDENT DATABASE ===");
        System.out.println("1. Add Student  2. View All  3. Search  4. Delete  5. Exit");

        boolean running = true;
        while (running) {
            System.out.print("\nChoice: ");
            int choice = sc.nextInt(); sc.nextLine();
            switch (choice) {
                case 1:
                    System.out.print("Name: "); String name = sc.nextLine();
                    System.out.print("Age: "); int age = sc.nextInt();
                    sc.nextLine();
                    System.out.print("Grade: "); String grade = sc.nextLine();
                    PreparedStatement ps = conn.prepareStatement(
                        "INSERT INTO students (name, age, grade) VALUES (?, ?, ?)");
                    ps.setString(1, name); ps.setInt(2, age); ps.setString(3, grade);
                    ps.executeUpdate();
                    System.out.println("Student added!");
                    break;
                case 2:
                    ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM students");
                    while (rs.next()) {
                        System.out.printf("%d | %s | %d | %s%n",
                            rs.getInt("id"), rs.getString("name"),
                            rs.getInt("age"), rs.getString("grade"));
                    }
                    break;
                case 5: running = false; break;
            }
        }
        conn.close();
        sc.close();
    }
}

7. MCQ Quiz with Answers

Question 1

JDBC stands for:

Question 2

Which class manages the database connection?

Question 3

PreparedStatement prevents:

Question 4

ResultSet is used to:

Question 5

rs.next() returns:

Question 6

executeUpdate() is for:

Question 7

executeQuery() is for:

Question 8

The ? in PreparedStatement represents:

Question 9

Which must be closed after use?

Question 10

JDBC URL format for MySQL:

8. Summary

JDBC connects Java to databases. Use DriverManager for connections, PreparedStatement for safe queries, and ResultSet for reading results. Always use PreparedStatement over Statement to prevent SQL injection. Close all resources using try-with-resources.

9. Next Chapter Recommendation

In Chapter 25: Java Streams and Lambda Expressions, we'll learn functional programming features introduced in Java 8.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·