• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Applications need to store and retrieve data from databases, but each database vendor has its own protocol and API. Without a standard abstraction, switching databases or supporting multiple databases would require rewriting all data access code.

Core Idea

Java Database Connectivity (JDBC) is a standard API that allows Java applications to interact with any relational database through a common interface. Database vendors provide JDBC drivers that implement the API. The core workflow is: connect → create statement → execute query → process results → close.

How It Works

The application loads a JDBC driver (e.g., com.mysql.cj.jdbc.Driver), gets a Connection via DriverManager.getConnection(), creates a Statement or PreparedStatement, executes SQL, and processes the ResultSet. PreparedStatement prevents SQL injection by pre-compiling queries with parameter placeholders.

Visual Explanation

java_jdbc App Java Application JDBC JDBC API (java.sql.*) App->JDBC Driver JDBC Driver (e.g., MySQL Connector/J) JDBC->Driver DB Database (MySQL, PostgreSQL, etc.) Driver->DB Steps JDBC Workflow S1 1. Load driver Steps->S1 S2 2. Get Connection S1->S2 S3 3. Create Statement S2->S3 S4 4. Execute Query S3->S4 S5 5. Process ResultSet S4->S5 S6 6. Close resources S5->S6

Semantic Network

semantic_jdbc THIS JDBC IO File I/O THIS--IO related EXC Exception Handling THIS--EXC built from SQL SQL THIS--SQL builds into OOP OOP in Java THIS--OOP related

Key Properties

  • Driver types: Type 1 (JDBC-ODBC bridge), Type 2 (native API), Type 3 (network protocol), Type 4 (pure Java, most common)
  • Statement types: Statement (static SQL), PreparedStatement (pre-compiled, prevents SQL injection), CallableStatement (stored procedures)
  • CRUD operations: Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE) via executeQuery() / executeUpdate()
  • Connection pooling: DataSource with connection pooling avoids expensive connection creation per request
  • Transaction management: Connection.setAutoCommit(false) enables manual transaction control with commit() and rollback()

Connections

Edge Cases & Gotchas

  • Resource leaks: Never forget to close Connection, Statement, and ResultSet — use try-with-resources
  • SQL injection: Never concatenate user input into SQL — always use PreparedStatement
  • Connection pool exhaustion: Long-running transactions or missing close() calls exhaust the pool
  • Driver class loading: In modern JDBC 4+, drivers auto-register via ServiceLoader (no Class.forName() needed)