Advanced
JDBC: Connecting Java to a Database
📂 Phase 5: Advanced Java — Streams, Lambda, Multithreading, DB (Days 22–26) · JavaJDBC (Java Database Connectivity) is the standard API that lets Java applications connect to, query, and update relational databases like MySQL or Oracle.
JDBC Architecture
Java Application
↓
JDBC API
↓
JDBC Driver (database-specific)
↓
Database (MySQL, Oracle, PostgreSQL, etc.)
Establishing a Connection
import java.sql.*;
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, user, password);
Statement vs PreparedStatement
| Type | Use Case | Security |
|---|---|---|
| Statement | Static SQL with no parameters | Vulnerable to SQL injection |
| PreparedStatement | Parameterized, reusable SQL | Safe — parameters are escaped automatically |
Querying Data with PreparedStatement
String sql = "SELECT name, email FROM users WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, 101); // safely binds the value, no string concatenation
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name") + " - " + rs.getString("email"));
}
Never build SQL by concatenating user input directly into a query string — this is exactly how SQL injection attacks happen. PreparedStatement with ? placeholders is the standard defense.
Performing an Insert (CRUD — Create)
String insertSql = "INSERT INTO users (name, email) VALUES (?, ?)";
PreparedStatement insertStmt = conn.prepareStatement(insertSql);
insertStmt.setString(1, "Vishwas");
insertStmt.setString(2, "vishwas@example.com");
int rowsAffected = insertStmt.executeUpdate();
System.out.println(rowsAffected + " row(s) inserted");
Always Close Your Resources
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement stmt = conn.prepareStatement(sql)) {
// use conn and stmt here
} catch (SQLException e) {
System.out.println("Database error: " + e.getMessage());
}
// try-with-resources automatically closes both, even if an exception occurs
Interview tip: "What's the difference between executeQuery() and executeUpdate()?" — executeQuery() is used for SELECT statements and returns a ResultSet. executeUpdate() is used for INSERT, UPDATE, and DELETE, and returns an int representing the number of rows affected.