Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 20 of 20 · 6 min read

Java JDBC databases and modern Java

Java JDBC notes with examples: connecting to a database, PreparedStatement, CRUD, ResultSet, transactions, SQL injection and modern Java up to Java 21.

What is JDBC?

JDBC (Java Database Connectivity) is the standard Java API for talking to relational databases such as MySQL, PostgreSQL, Oracle and SQLite. Your code uses the interfaces in java.sql; a driver (a jar file from the database vendor) does the database-specific work.

DatabaseDriver jarURL example
SQLitesqlite-jdbcjdbc:sqlite:school.db
MySQLmysql-connector-jjdbc:mysql://localhost:3306/school
PostgreSQLpostgresqljdbc:postgresql://localhost:5432/school

SQLite needs no server: the whole database is one file, which makes it ideal for practice.

The five steps

  1. Add the driver jar to the classpath.
  2. Open a Connection with DriverManager.getConnection(url, user, password).
  3. Create a PreparedStatement with SQL.
  4. Execute it: executeQuery() for SELECT, executeUpdate() for INSERT, UPDATE and DELETE.
  5. Close everything; try-with-resources does it for you.

Connecting and creating a table

import java.sql.*;

public class SchoolDb {
    static final String URL = "jdbc:sqlite:school.db";

    public static void main(String[] args) throws SQLException {
        try (Connection con = DriverManager.getConnection(URL);
             Statement st = con.createStatement()) {
            st.executeUpdate("""
                CREATE TABLE IF NOT EXISTS student (
                    roll  INTEGER PRIMARY KEY,
                    name  TEXT NOT NULL,
                    marks INTEGER
                )""");
            System.out.println("Table ready");
        }
    }
}

Compile and run with the driver on the classpath, for example java -cp ".;sqlite-jdbc.jar" SchoolDb on Windows (use : instead of ; on Linux and macOS).

Insert with PreparedStatement

String sql = "INSERT INTO student (roll, name, marks) VALUES (?, ?, ?)";
try (Connection con = DriverManager.getConnection(URL);
     PreparedStatement ps = con.prepareStatement(sql)) {
    ps.setInt(1, 101);
    ps.setString(2, "Asha");
    ps.setInt(3, 91);
    int rows = ps.executeUpdate();
    System.out.println(rows + " row inserted");
}

Each ? is a placeholder, filled by setInt, setString, setDouble, setDate and so on. Positions start at 1.

Read with ResultSet

try (Connection con = DriverManager.getConnection(URL);
     PreparedStatement ps = con.prepareStatement(
         "SELECT roll, name, marks FROM student WHERE marks >= ? ORDER BY marks DESC")) {
    ps.setInt(1, 60);
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            System.out.printf("%d %-8s %d%n",
                rs.getInt("roll"), rs.getString("name"), rs.getInt("marks"));
        }
    }
}

A ResultSet starts before the first row; each rs.next() moves to the next row and returns false when there are no more.

Update and delete

try (Connection con = DriverManager.getConnection(URL);
     PreparedStatement ps = con.prepareStatement("UPDATE student SET marks = ? WHERE roll = ?")) {
    ps.setInt(1, 95);
    ps.setInt(2, 101);
    System.out.println(ps.executeUpdate() + " row updated");
}

DELETE FROM student WHERE roll = ? works the same way. executeUpdate returns how many rows changed.

Why PreparedStatement? SQL injection

Never build SQL by joining strings with user input:

// DANGEROUS
String sql = "SELECT * FROM users WHERE name = '" + name + "'";

If someone types ' OR '1'='1 as their name, the query returns every user. This attack is SQL injection. With a PreparedStatement, the value is sent separately from the SQL and is always treated as data, never as code. It is also faster when the same statement runs many times.

Transactions

By default every statement is committed immediately. For changes that must all succeed or all fail, such as moving money between two accounts, use a transaction:

try (Connection con = DriverManager.getConnection(URL)) {
    con.setAutoCommit(false);
    try (PreparedStatement debit = con.prepareStatement(
             "UPDATE account SET balance = balance - ? WHERE id = ?");
         PreparedStatement credit = con.prepareStatement(
             "UPDATE account SET balance = balance + ? WHERE id = ?")) {
        debit.setDouble(1, 500);  debit.setInt(2, 1);  debit.executeUpdate();
        credit.setDouble(1, 500); credit.setInt(2, 2); credit.executeUpdate();
        con.commit();
    } catch (SQLException e) {
        con.rollback();            // undo both changes
        throw e;
    }
}

The DAO pattern

Keep SQL out of the rest of the program: a DAO (Data Access Object) class has methods such as save(Student s), findByRoll(int roll) and findAll(), and only it uses JDBC. The rest of the app works with Student objects.

Modern Java at a glance

VersionFeatureExample
Java 8lambdas, streams, java.time, Optionallist.stream().filter(...)
Java 10var for local variablesvar list = new ArrayList<String>();
Java 11String.isBlank, strip, repeat; Files.readString"ab".repeat(3)
Java 14switch expressionscase 1, 2 -> "low";
Java 15text blocks""" multi-line strings """
Java 16records; pattern matching for instanceofif (o instanceof String s)
Java 17sealed classessealed interface Shape permits Circle, Square
Java 21pattern matching for switch; record patterns; virtual threadssee below

Pattern matching for switch (Java 21)

sealed interface Shape permits Circle, Square { }
record Circle(double r) implements Shape { }
record Square(double side) implements Shape { }

static double area(Shape s) {
    return switch (s) {
        case Circle c -> Math.PI * c.r() * c.r();
        case Square q -> q.side() * q.side();
    };
}

Because Shape is sealed, the compiler knows these are the only two kinds, so no default is needed, and adding a new shape makes every incomplete switch a compile error.

Common mistakes

  • Missing driver jar: "No suitable driver found for jdbc:...".
  • Building SQL with + and user input (SQL injection).
  • Starting PreparedStatement parameter positions at 0; they start at 1.
  • Reading a ResultSet without calling rs.next() first.
  • Not closing connections, so the database runs out of them; use try-with-resources.

Key points

  • JDBC = Connection, PreparedStatement, ResultSet, plus a vendor driver.
  • executeQuery for SELECT; executeUpdate for INSERT, UPDATE, DELETE and DDL.
  • Always use PreparedStatement with ? placeholders to prevent SQL injection.
  • setAutoCommit(false), commit() and rollback() make a group of changes all-or-nothing.
  • Modern Java adds var, records, text blocks, switch expressions, sealed types and pattern matching.

Practice questions

1. Which method runs a SELECT, and which runs an INSERT?

executeQuery() for SELECT (returns a ResultSet); executeUpdate() for INSERT (returns the number of rows changed).

2. Write the code to delete the student with roll 105 using a PreparedStatement.
try (Connection con = DriverManager.getConnection(URL);
     PreparedStatement ps = con.prepareStatement("DELETE FROM student WHERE roll = ?")) {
    ps.setInt(1, 105);
    System.out.println(ps.executeUpdate() + " row deleted");
}
3. What is SQL injection, and how does PreparedStatement stop it?

SQL injection is when user input changes the meaning of an SQL query because it was pasted into the SQL text. A PreparedStatement sends the input separately as a parameter, so it is always treated as a value, never as SQL.

4. Print the number of students with marks below 40.
try (Connection con = DriverManager.getConnection(URL);
     PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM student WHERE marks < 40");
     ResultSet rs = ps.executeQuery()) {
    rs.next();
    System.out.println(rs.getInt(1));
}
5. Why turn off auto-commit for a money transfer?

So the debit and the credit form one transaction: if either fails, rollback() undoes both, and money is never lost or created.