Skip to content
AgileLogics
5 min read

JDBC & Database Access

Prerequisites: Networking basics

JDBC is Java's standard API for talking to a relational database — a driver (one per database vendor) implements it against a specific database like PostgreSQL or SQLite.

import java.sql.*;

try (Connection conn = DriverManager.getConnection("jdbc:sqlite:app.db")) {
    PreparedStatement stmt = conn.prepareStatement(
        "SELECT name FROM users WHERE id = ?"
    );
    stmt.setInt(1, 1);

    ResultSet rs = stmt.executeQuery();
    if (rs.next()) {
        System.out.println(rs.getString("name"));
    }
} catch (SQLException e) {
    System.out.println("Database error: " + e.getMessage());
}

In real projects, an ORM like Hibernate (or Spring Data JPA built on it) maps rows to objects automatically, but understanding plain JDBC first makes clear what the ORM is doing underneath.

Common mistakes

  • Building a query with string concatenation ("...WHERE id = " + userInput) instead of a PreparedStatement's ? placeholders — this opens the door to SQL injection.