← Back to Chapters

JDBC Architecture

☕ JDBC Architecture

? Quick Overview

JDBC (Java Database Connectivity) Architecture defines how a Java application communicates with a database. It acts as a bridge between Java programs and different databases using standardized APIs and database-specific drivers.

? Key Concepts

  • JDBC API — Interfaces and classes provided by Java
  • JDBC Driver — Database-specific implementation
  • DriverManager — Manages JDBC drivers
  • Connection — Represents database session
  • Statement — Executes SQL queries
  • ResultSet — Holds query results

? Interactive Architecture Flow

Ready to execute query...
 
Java Application
JDBC API / Mgr
JDBC Driver
Database (MySQL)

? Syntax / Theory

JDBC follows a layered architecture:

  1. Java Application
  2. JDBC API (java.sql, javax.sql)
  3. JDBC Driver Manager
  4. JDBC Driver
  5. Database

? Code Example(s)

? View Code Example
// Load JDBC driver and establish database connection
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb","root","password");
? View Code Example
// Execute SQL query using Statement and read ResultSet
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

? Live Output / Explanation

What Happens Internally?

  • DriverManager loads the appropriate JDBC driver
  • Connection object opens a session with the database
  • Statement sends SQL to the database
  • ResultSet stores data returned by the database

✅ Tips & Best Practices

  • Always close Connection, Statement, and ResultSet
  • Use PreparedStatement to prevent SQL Injection
  • Use connection pooling for better performance
  • Handle exceptions properly using try-catch

? Try It Yourself

  • Connect Java application to MySQL or Oracle database
  • Replace Statement with PreparedStatement
  • Fetch data using column names instead of indexes
  • Draw JDBC architecture diagram on paper