Beginner Reference Manual • Chapter 9

Connecting Java to Databases (JDBC Architecture)

Learn how Java talks to databases using JDBC, connection strings, safe PreparedStatement queries, ResultSet navigation, and transaction safety.

Variables only store data while the computer is turned on. When you close your app, that data vanishes! To save data permanently, apps use Relational Databases. JDBC is Java's bridge for reading and writing database records.

9.1. 1. What is a Database & JDBC Drivers

Definition: JDBC (Java Database Connectivity) is a Java API that enables Java applications to connect and execute SQL queries against relational databases.

Core Working Principles:

📞 Layman Analogy: Placing a Phone Call to a Filing Office

• DriverManager: The telephone network operator establishing your call.
• Connection: The active connected phone line between Java and the database.
• SQL Query: Asking the filing clerk over the phone: "Please send me customer records for ID #101."

5-Marks Exam Scoring Points
  • JDBC connects Java apps to relational databases.
  • DriverManager establishes Connection instances.
  • java.sql interfaces decouple Java code from vendor database implementations.

9.2. 2. Safe Queries: Statement vs PreparedStatement

Definition: Classes used to execute SQL commands against database connections.

Core Working Principles:

Query Mechanism SQL Injection Protection Performance
Statement Vulnerable (Unsafe String Concatenation) Slower for repeated queries
PreparedStatement 🏆 100% Protected (Uses ? Placeholders) Faster (Pre-compiled query plan)
5-Marks Exam Scoring Points
  • PreparedStatement protects applications against SQL Injection attacks.
  • Use parameterized '?' placeholders to bind dynamic inputs safely.
  • Always close Connections and Statements after use.

9.3. 3. Reading Results & Transaction Safety

Definition: ResultSet navigates query rows, and Transactions guarantee multi-step updates complete atomically.

Core Working Principles:

String sql = "SELECT * FROM users WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
    pstmt.setInt(1, 101);
    ResultSet rs = pstmt.executeQuery();
    
    while (rs.next()) {
        System.out.println("User Name: " + rs.getString("username"));
    }
}
5-Marks Exam Scoring Points
  • ResultSet provides cursor navigation through database query rows.
  • commit() saves database transaction changes permanently.
  • rollback() resets database state if an error occurs during transaction updates.

✍️ Chapter 9 Reference Exercises & Review Problems

Exercise 9.1: Why is `PreparedStatement` safer than standard `Statement` when accepting user input?
Step-by-Step Explanation for Beginners:
1. **SQL Injection Attack:** Standard `Statement` joins user input string directly into SQL code. Attackers can type `' OR '1'='1` to bypass passwords!
2. **PreparedStatement Protection:** Uses `?` placeholders which treat user inputs strictly as plain literal values, making it impossible for hacker input to run as code.
Exercise 9.2: What is the purpose of `conn.rollback()` in database transactions?
Step-by-Step Explanation for Beginners:
If a bank transfer involves (1) deducting $100 from Account A and (2) adding $100 to Account B, if Step 2 fails halfway through, `conn.rollback()` cancels Step 1 automatically so money is never lost!