JDBC (Java Database Connectivity) is a Java API that allows Java programs to connect and interact with databases.
👉 It is used to:
JDBC acts as a bridge between:
📊 Concept Diagram (Description) Java Program → JDBC API → JDBC Driver → Database
JDBC API
JDBC Driver Manager
JDBC Driver
Database
| Type | Description |
|---|---|
| Type 1 | JDBC-ODBC Bridge |
| Type 2 | Native API |
| Type 3 | Network Protocol |
| Type 4 | Thin Driver (most used) |
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close();
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
| Interface | Purpose |
|---|---|
| Connection | Connect to database |
| Statement | Execute SQL |
| PreparedStatement | Precompiled SQL |
| ResultSet | Store result |
PreparedStatement ps = con.prepareStatement(
"INSERT INTO student VALUES (?, ?)");
ps.setInt(1, 1);
ps.setString(2, "Ali");
ps.executeUpdate();
👉 Advantages:
| Type | Use |
|---|---|
| Statement | Simple SQL |
| PreparedStatement | Parameterized queries |
| CallableStatement | Stored procedures |
try-catch blocksSQLExceptioncatch(SQLException e) {
System.out.println(e.getMessage());
}
con.setAutoCommit(false);
// SQL operations
con.commit(); // save changes
con.rollback(); // undo changes
📊 JDBC Working Diagram:
Arrows showing flow of data and commands
JDBC = Java Database Connectivity
Connects Java to database
Steps:
Use PreparedStatement for security
Handle exceptions properly
Open this section to load past papers