Working with JDBC

1. Loading JDBC Drivers

EraDetail
ModernSPI auto-load via META-INF/services
LegacyClass.forName("com.mysql.cj.jdbc.Driver")

2. Establishing Connections

Example: Connection

String url = "jdbc:postgresql://localhost:5432/mydb";
try (Connection conn = DriverManager.getConnection(url, "user", "pass")) {
    conn.setAutoCommit(false);
    // ... operations
    conn.commit();
}
URL PatternDatabase
jdbc:postgresql://host:5432/dbPostgreSQL
jdbc:mysql://host:3306/dbMySQL
jdbc:oracle:thin:@host:1521:sidOracle
jdbc:h2:mem:testdbH2 in-memory

3. Using Statement

MethodUse
executeQuery(sql)SELECT → ResultSet
executeUpdate(sql)INSERT/UPDATE/DELETE → row count
execute(sql)Any (returns boolean)
Warning: Never concatenate user input into SQL — use PreparedStatement to prevent SQL injection.

4. Using PreparedStatement

Example: PreparedStatement

String sql = "SELECT * FROM users WHERE email = ? AND active = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, email);
    ps.setBoolean(2, true);
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) { ... }
    }
}
SetterType
setString(idx, val)String
setInt/setLong/setDoubleNumeric
setObject(idx, val, sqlType)Generic
setNull(idx, sqlType)NULL

5. Using CallableStatement

AspectDetail
SQL{call procedure(?, ?)}
OUT paramsregisterOutParameter(idx, type)
Get resultgetXxx(idx) after execute

6. Working with ResultSet

MethodUse
next()Move to next row
getString(col) / getInt(col)By name or index
wasNull()Check if last value was SQL NULL
getMetaData()Column info

7. Handling Transactions

MethodDetail
setAutoCommit(false)Begin manual mode
commit() / rollback()Finalize
setSavepoint() / rollback(sp)Partial rollback
setTransactionIsolation(level)READ_COMMITTED, etc.

8. Using Batch Processing

Example: Batch insert

try (PreparedStatement ps = conn.prepareStatement("INSERT INTO log VALUES (?, ?)")) {
    for (LogEntry e : entries) {
        ps.setString(1, e.message());
        ps.setTimestamp(2, Timestamp.from(e.time()));
        ps.addBatch();
    }
    int[] counts = ps.executeBatch();
}
MethodUse
addBatch()Queue statement
executeBatch()Run all
clearBatch()Reset queue

9. Handling SQL Exceptions

AspectDetail
SQLExceptionBase for SQL errors
getSQLState()5-char SQLSTATE
getErrorCode()Vendor code
getNextException()Chained exceptions
SubclassesSQLIntegrityConstraintViolationException, etc.

10. Using Connection Pools

PoolDetail
HikariCPIndustry standard, fastest
Apache DBCP2Legacy
DataSourceJDBC-standard interface for pools
Why pool?Connection setup is expensive

11. Closing Resources Properly

OrderReason
ResultSet → Statement → ConnectionReverse of opening
try-with-resourcesHandles automatically
Pooled connectionclose() returns to pool

12. Working with Database Metadata

MethodReturns
conn.getMetaData()DatabaseMetaData
getTables / getColumns / getPrimaryKeysSchema info
getDriverVersion / getDatabaseProductNameVersion info