Java Notes
Complete introduction to JDBC — Java Database Connectivity concepts, API overview, driver types, and how Java applications communicate with databases.
What is JDBC?
JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with relational databases. It provides a standard interface for connecting to databases, executing SQL queries, and processing results — regardless of which database you use.
| Java Application | ────▶ | JDBC API | ────▶ | Database |
|---|---|---|---|---|
| (Driver) | (MySQL/ | |||
| ◀──── | ◀──── | Oracle/ | ||
| PostgreSQL) |
Why JDBC?
- Database Independence — Same Java code works with MySQL, Oracle, PostgreSQL (just change the driver)
- Standard API — Consistent interface across all databases
- Full SQL Support — Execute any SQL statement the database supports
- Transaction Control — Manage commits, rollbacks, savepoints
- Foundation for ORMs — Hibernate, JPA, MyBatis all use JDBC underneath
JDBC Driver Types
Type 1: JDBC-ODBC Bridge (Deprecated in Java 8)
- Translates JDBC calls to ODBC calls
- Requires ODBC driver installed on client
- Slow performance, not portable
- Removed in Java 8 — don't use
Type 2: Native-API Driver (Partial Java)
- Uses database vendor's native C/C++ libraries
- Better performance than Type 1
- Requires native libraries on client machine
- Example: Oracle OCI driver
Type 3: Network Protocol Driver (Pure Java)
- Pure Java driver talks to a middleware server
- Middleware translates to database protocol
- No client-side native libraries needed
- Good for internet applications
Type 4: Thin Driver (Pure Java, Direct) ⭐ Most Common
- Pure Java, communicates directly with database
- No middleware, no native libraries
- Best performance, most portable
- This is what we use: MySQL Connector/J, PostgreSQL JDBC, etc.
// Type 4 driver examples (Maven dependencies):
// MySQL: mysql:mysql-connector-java:8.0.33
// PostgreSQL: org.postgresql:postgresql:42.6.0
// Oracle: com.oracle.database.jdbc:ojdbc8:21.9.0.0
// SQL Server: com.microsoft.sqlserver:mssql-jdbc:12.4.1.jre11Basic JDBC Workflow
import java.sql.*;
public class JDBCBasicExample {
public static void main(String[] args) {
// JDBC URL format: jdbc:subprotocol:subname
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
// Step 1: Establish connection
// Step 2: Create statement
// Step 3: Execute query
// Step 4: Process results
// Step 5: Close resources
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, email FROM users")) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
System.out.printf("ID: %d, Name: %s, Email: %s%n", id, name, email);
}
} catch (SQLException e) {
System.err.println("SQL Error: " + e.getMessage());
System.err.println("SQL State: " + e.getSQLState());
System.err.println("Error Code: " + e.getErrorCode());
}
}
}JDBC URL Formats
// MySQL
"jdbc:mysql://hostname:3306/database_name"
"jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC"
// PostgreSQL
"jdbc:postgresql://hostname:5432/database_name"
// Oracle
"jdbc:oracle:thin:@hostname:1521:SID"
"jdbc:oracle:thin:@//hostname:1521/service_name"
// SQL Server
"jdbc:sqlserver://hostname:1433;databaseName=mydb"
// H2 (in-memory for testing)
"jdbc:h2:mem:testdb"
"jdbc:h2:file:./data/mydb"
// SQLite
"jdbc:sqlite:path/to/database.db"Setting Up MySQL with JDBC
Step 1: Add MySQL Connector Dependency
// Gradle
implementation 'mysql:mysql-connector-java:8.0.33'Step 2: Create Database and Table
CREATE DATABASE IF NOT EXISTS student_db;
USE student_db;
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) UNIQUE,
age INT CHECK (age >= 0 AND age <= 150),
gpa DECIMAL(3, 2),
enrollment_date DATE DEFAULT (CURRENT_DATE),
is_active BOOLEAN DEFAULT TRUE
);
INSERT INTO students (name, email, age, gpa) VALUES
('Alice Johnson', 'alice@example.com', 20, 3.85),
('Bob Smith', 'bob@example.com', 22, 3.42),
('Charlie Brown', 'charlie@example.com', 21, 3.91);Step 3: First Complete Program
import java.sql.*;
public class FirstJDBCProgram {
private static final String URL = "jdbc:mysql://localhost:3306/student_db";
private static final String USER = "root";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
// Load driver (optional in JDBC 4.0+ with META-INF/services)
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded successfully!");
} catch (ClassNotFoundException e) {
System.err.println("MySQL Driver not found. Add to classpath.");
return;
}
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
System.out.println("Connected to database!");
System.out.println("Database: " + conn.getCatalog());
System.out.println("Auto-commit: " + conn.getAutoCommit());
DatabaseMetaData meta = conn.getMetaData();
System.out.println("Driver: " + meta.getDriverName() + " " + meta.getDriverVersion());
System.out.println("Database Product: " + meta.getDatabaseProductName());
} catch (SQLException e) {
System.err.println("Connection failed: " + e.getMessage());
}
}
}Driver loaded successfully! Connected to database!
JDBC vs ORM (Hibernate/JPA)
| Feature | JDBC | Hibernate/JPA |
|---|---|---|
| Learning curve | Lower | Higher |
| Control | Full SQL control | Abstracted |
| Performance | Can be tuned precisely | May generate inefficient SQL |
| Boilerplate | More code | Less code |
| Caching | Manual | Built-in (L1, L2) |
| Portability | SQL dialect-dependent | Database-independent HQL |
| Best for | Simple apps, performance-critical | Complex domain models |
Key insight: Understanding JDBC is essential even if you use Hibernate — debugging ORM issues requires JDBC knowledge.
Interview Questions
Q1: What is JDBC and why is it needed?
Answer: JDBC is a Java API for database interaction. It provides a standard interface so Java applications can work with any relational database using the same code — only the driver and connection URL change.
Q2: Name the four types of JDBC drivers. Which is most commonly used?
Answer: Type 1 (JDBC-ODBC Bridge), Type 2 (Native-API), Type 3 (Network Protocol), Type 4 (Thin/Direct). Type 4 is most common — it's pure Java, communicates directly with the database, and offers the best performance and portability.
Q3: What are the main interfaces in JDBC API?
Answer: Connection (database session), Statement (static SQL), PreparedStatement (parameterized SQL), CallableStatement (stored procedures), ResultSet (query results), and DriverManager (connection factory).
Q4: What is the difference between Statement and PreparedStatement?
Answer: Statement executes static SQL strings (vulnerable to SQL injection). PreparedStatement uses parameterized queries with placeholders (?), preventing SQL injection, enabling query plan caching, and supporting binary data.
Q5: What does Class.forName() do in JDBC?
Answer: It loads the JDBC driver class into memory, triggering its static initializer which registers the driver with DriverManager. In JDBC 4.0+ (Java 6+), this is automatic via ServiceLoader (META-INF/services), making it optional.
Q6: What is the try-with-resources pattern and why use it with JDBC?
Answer: It automatically closes resources (Connection, Statement, ResultSet) when the try block exits — even on exceptions. This prevents resource leaks which can exhaust database connection pools.
Summary
In this chapter, we learned about JDBC Introduction in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JDBC Introduction.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, jdbc, introduction, jdbc introduction
Related Java Master Course Topics