Java · Module 12 · Lesson 11 min read

Databases with JDBC

What is JDBC?

JDBC (Java Database Connectivity) is the standard API for talking to SQL databases like PostgreSQL, MySQL and SQLite. You add the database's driver (a library) to your project.

Connecting

Java
String url = "jdbc:postgresql://localhost:5432/school";
try (Connection conn = DriverManager.getConnection(url, "user", "password")) {
    // use the connection
}

PreparedStatement — always! 🛡️

Java
String sql = "SELECT name, marks FROM students WHERE marks > ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setInt(1, 80);                       // fill the first ?
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getString("name") + " " + rs.getInt("marks"));
        }
    }
}

⚠️ Never build SQL by joining strings with user input, like "... WHERE name = '" + input + "'". That allows SQL injection attacks. ? placeholders are escaped safely.

Running queries

MethodUse forReturns
executeQuery()SELECTResultSet
executeUpdate()INSERT, UPDATE, DELETEnumber of rows changed

Transactions — all or nothing

Java
conn.setAutoCommit(false);
try {
    withdraw(conn, from, 100);
    deposit(conn, to, 100);
    conn.commit();          // both succeed ✅
} catch (SQLException e) {
    conn.rollback();        // undo everything ↩️
}

In real projects

  • Use a connection pool like HikariCP; opening connections is slow.
  • Many teams use JPA / Hibernate or Spring Data, which map tables to Java classes so you write less SQL.
  • Keep passwords in environment variables, never in code.

Example

Java
import java.sql.*;

public class StudentDb {
    public static void main(String[] args) {
        String url = System.getenv("DB_URL");   // e.g. jdbc:postgresql://host:5432/postgres
        String user = System.getenv("DB_USER");
        String pass = System.getenv("DB_PASS");

        try (Connection conn = DriverManager.getConnection(url, user, pass)) {
            try (PreparedStatement insert = conn.prepareStatement(
                    "INSERT INTO students (name, marks) VALUES (?, ?)")) {
                insert.setString(1, "Ana");
                insert.setInt(2, 92);
                System.out.println("Rows added: " + insert.executeUpdate());
            }

            try (PreparedStatement query = conn.prepareStatement(
                    "SELECT name, marks FROM students WHERE marks >= ? ORDER BY marks DESC")) {
                query.setInt(1, 80);
                try (ResultSet rs = query.executeQuery()) {
                    while (rs.next()) {
                        System.out.println(rs.getString("name") + " → " + rs.getInt("marks"));
                    }
                }
            }
        } catch (SQLException e) {
            System.out.println("Database error: " + e.getMessage());
        }
    }
}