Java - JDBC Basics

JDBC Basics

Quick Example (H2 in-memory)

import java.sql.*;
try (Connection c = DriverManager.getConnection("jdbc:h2:mem:test")) {
  c.setAutoCommit(false);
  try (PreparedStatement ps = c.prepareStatement("select 1")) {
    try (ResultSet rs = ps.executeQuery()) { rs.next(); System.out.println(rs.getInt(1)); }
  }
  c.commit();
}

Best Practices

  • Use PreparedStatement to avoid SQL injection and enable plan caching.
  • Always close resources (try-with-resources).
  • Manage transactions explicitly for multi-statement operations.
Architect note: Consider connection pools (HikariCP), proper isolation levels, and timeout settings.