Connecting to a Database
1. Connection in Detail (beginner)
Connection = live phone line to DB (DriverManager.getConnection(url, user, pass)). Check con.isValid(2) (2-sec ping!). One per app (or pool!), close when done!
2. Code — Robust Connect (exam pattern!)
import java.sql.*;
public class Conn {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
// try-with-resources (auto-close! no leak!)
try (Connection con = DriverManager.getConnection(url, "root", "pass")) {
System.out.println("connected! valid=" + con.isValid(2));
System.out.println("db=" + con.getCatalog());
// ... statements here! (same block!)
} catch (SQLException e) {
System.out.println("fail: " + e.getMessage());
System.out.println("code=" + e.getErrorCode() + " state=" + e.getSQLState());
} // con auto-closed here!
}
}
3. Failure Table (exam debug!)
| Message | Cause | Fix |
|---|---|---|
| No suitable driver | URL wrong / jar missing! | check jdbc:mysql:// + jar! |
| Access denied | user/pass wrong! | GRANT + correct pass! |
| Communications link | server down/port! | start MySQL, check 3306! |
4. Pool Taste (real apps!)
New connection = slow (~100ms!). Pool (HikariCP) reuses 10 ready lines. Beginners: one connection; projects: pool!
5. Exam Points
- Connect +
isValid+ try-with-resources — 5-7 marks, frequent. - Three failure causes — 3 marks, frequent.