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.

Feb 22, 20264 views0 likes0 fires
18px

[!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 slotString safeSql = "SELECT

FROM users WHERE username = ?";

// 2. PreparedStatement pre-compiles the query defensivelyPreparedStatement 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();

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
2 questions5 min

Continue Learning

37. Annotations & Reflection

Advanced
10 min

38. The JVM Garbage Collector

Advanced
12 min

39. Introduction to Spring Boot

Advanced
12 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 Java Programming: From Zero to EnterpriseAll Categories