Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
4. Advanced Java & Frameworks
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

36. JDBC: Connecting to SQL Databases

Bridging your application to a persistent PostgreSQL/MySQL database.

Java Programming: From Zero to Enterprise
4. Advanced Java & Frameworks
February 22, 2026
63
A

[!NOTE] Until now, variables disappeared when the program closed. To build real applications, you need persistent state. Java Database Connectivity (JDBC) is the official API used to connect Java directly to relational databases.

The JDBC Architecture Pipeline

Whether you are connecting to Oracle, PostgreSQL, or MySQL, JDBC uses the exact same interface code. You just drop in the correct "Driver" binary file provided by your specific database company.

The Pipeline:

  1. Securely Connect to the Database.
  2. Create a SQL Statement.
  3. Execute the Statement.
  4. Process the returned ResultSet.
  5. Close the connection to prevent memory leaks!

Example: Selecting Data

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DatabaseExample {
    public static void main(String[] args) {
        
        String url = "jdbc:postgresql://localhost:5432/my_company";
        String user = "admin";
        String pwd = "super_secret_password";

        // We wrap database connections in Try-Catch because networking can fail!
        try (Connection conn = DriverManager.getConnection(url, user, pwd)) {

            System.out.println("Connection physically established to PostgreSQL!");

            // Create the Query Object
            Statement stmt = conn.createStatement();
            
            // Execute the raw query safely!
            String sql = "SELECT id, username, permission_level FROM users";
            ResultSet rs = stmt.executeQuery(sql);

            // Iterate through the results vertically!
            while (rs.next()) {
                // Extract column data from the current row
                int id = rs.getInt("id");
                String name = rs.getString("username");
                System.out.println("Row Scanned! ID: " + id + ", Name: " + name);
            }

        } catch (Exception e) {
            System.err.println("Fatal Database Connection Error!");
            e.printStackTrace();
        }
    }
}

The Terror of SQL Injection

If your application asks the user to type in their "Username" into an HTML form to trigger a SELECT check, a malicious hacker can type in exactly this string: '; DROP TABLE users; --

If you blindly concatenate their string directly into your raw SQL format: "SELECT * FROM users WHERE name = '" + userInput + "';"

You will physically transmit the command to drop the entire table, instantly wiping production data.

The Fix: PreparedStatement

Never, ever use string concatenation for SQL queries. Always use PreparedStatement. It mathematically escapes hacker strings safely as raw text.

// 1. The '?' acts as an armored parameter slot
String safeSql = "SELECT * FROM users WHERE username = ?";

// 2. PreparedStatement pre-compiles the query defensively
PreparedStatement pstmt = conn.prepareStatement(safeSql);

// 3. You inject the user's string. If they typed '; DROP TABLE', it is safely escaped!
pstmt.setString(1, userInput);

ResultSet rs = pstmt.executeQuery();

JDBC in Real Applications

JDBC is the low-level bridge between Java and relational databases. Even if you later use Spring Data JPA or Hibernate, understanding JDBC helps you understand connections, statements, result sets, and transactions.

Use try-with-resources

String sql = "SELECT id, username FROM users WHERE username = ?";

try (
    Connection connection = dataSource.getConnection();
    PreparedStatement statement = connection.prepareStatement(sql)
) {
    statement.setString(1, username);
    try (ResultSet rs = statement.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getString("username"));
        }
    }
}

This pattern closes the connection, statement, and result set automatically.

Transaction Shape

connection.setAutoCommit(false);
try {
    // execute multiple related updates
    connection.commit();
} catch (SQLException e) {
    connection.rollback();
    throw e;
}

Common Mistakes

  • Building SQL by concatenating user input.
  • Forgetting to close database resources.
  • Not using transactions for multi-step updates.
  • Fetching too many rows when pagination is needed.

Mini Practice

Write a prepared statement for finding a user by email. Then write a second example that updates marks and commits only when both related updates succeed.

Practice Lab: Prepared Statement Design

Write JDBC code shape that avoids SQL injection and resource leaks.

  1. Write SQL with a parameter placeholder: SELECT * FROM users WHERE email = ?.
  2. Create a PreparedStatement.
  3. Set the email parameter using setString.
  4. Read rows with ResultSet and rs.next().
  5. Wrap resources in try-with-resources.

Goal: Practice the safe JDBC query shape before connecting to a real database.

Revision Checkpoint

  • JDBC: Java API for relational database access.
  • Connection: Link to database.
  • PreparedStatement: Parameterized SQL; helps prevent injection.
  • ResultSet: Cursor over returned rows.
  • Transaction: Commit all related changes or roll back together.

Before the quiz: Explain why user input should never be concatenated into SQL.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: JDBC
10 questions5 min
Lesson 6 of 11 in 4. Advanced Java & Frameworks
Previous in 4. Advanced Java & Frameworks
35. Multithreading & Concurrency Basics
Next in 4. Advanced Java & Frameworks
37. Annotations & Reflection
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories