Part 02:
1. What JDBC actually is ?
JDBC = Java Database Connectivity.
It’s just a set of interfaces + APIs in the JDK that let Java code interact with any relational database (MySQL,
PostgreSQL, Oracle, etc.).
Vendors (like PostgreSQL or MySQL) provide drivers (JARs) that implement the JDBC interfaces.
So when you write:
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/mydb", "user",
"pass");
The PostgreSQL JDBC driver actually handles the connection.
2. Core JDBC building blocks
The usual chain of objects is:
1. DriverManager → loads the DB driver class (old style).
DataSource → better, used with connection pools.
2. Connection → represents a live DB connection (like logging into the DB).
3. Statement/PreparedStatement/CallableStatement → send SQL queries.
4. ResultSet → holds the query results (like a cursor you iterate through).
3. Transactions
Databases usually run in auto-commit mode — every statement is immediately committed.
But in backend apps, you often want transactions (a group of statements succeed or fail together).
4. Connection pooling
Creating a DB connection is expensive (handshake, auth, setup).
Backend servers don’t open a new connection per request — they use a connection pool.
Most common: HikariCP.
It keeps a pool of live connections and hands them out when needed.
5. Performance tricks you should know
● Use PreparedStatement always (better perf + safe).
● Use batching for mass inserts.
● Use setFetchSize() if fetching large result sets (avoids loading all rows into memory).
● Transactions should be short to avoid locks and contention.
6. Migration tools (important in real projects)
You don’t just “change the DB manually”. Use tools:
● Flyway or Liquibase → manage schema changes with versioned scripts.
Example Flyway script (V1__create_users.sql):
⚡ In real backend projects:
● You’ll rarely write raw JDBC everywhere — frameworks like Spring JDBC or JPA/Hibernate sit on top.
● But you must understand JDBC fundamentals to debug slow queries, deadlocks, connection pool
leaks, etc.