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:
- Relational Database: Digital filing cabinets storing data permanently in tables of rows and columns (e.g. MySQL, PostgreSQL).
- JDBC Driver: Software translator that converts Java commands into database-specific communication protocols.
• 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:
- Statement: Executes raw static SQL strings (Vulnerable to SQL Injection attacks!).
- PreparedStatement: Pre-compiles SQL queries using parameterized placeholders (
?), completely neutralizing hacker SQL Injection attacks!
| 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:
- ResultSet: Data cursor that steps through returned database query rows (`rs.next()`).
- Transaction Control: `conn.setAutoCommit(false)`, `conn.commit()`, `conn.rollback()` ensuring multi-step updates complete together safely.
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
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.
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!