0Pricing
Java Academy · Lesson

PreparedStatement

Safe parameterized queries.

PreparedStatement is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why PreparedStatement?

Building SQL by concatenating user input is dangerous and slow.

PreparedStatement solves both problems:

  • Safety — values are sent separately from the SQL, preventing SQL injection.
  • Performance — the database can parse and plan the query once, then reuse it.

The SQL Injection Problem

Consider building a query with string concatenation. If a user types '; DROP TABLE users; -- as their name, the concatenated SQL executes that as a command.

This is SQL injection, one of the oldest and most damaging web vulnerabilities. PreparedStatement makes it impossible by design.

public class Main {
    public static void main(String[] args) {
        String userInput = "'; DROP TABLE users; --";
        // Dangerous: never do this
        String unsafe = "SELECT * FROM users WHERE name = '" + userInput + "'";
        System.out.println("Injected SQL becomes:");
        System.out.println(unsafe);
    }
}

Placeholders

In a PreparedStatement, you write a ? for each value you will supply later.

Then you bind values with typed setters:

  • ps.setString(1, name)
  • ps.setInt(2, age)

Parameter indexes are 1-based, matching the order of the ? marks.

A Safe Query

Create the statement with prepareStatement, bind parameters, then call executeQuery.

The value never touches the SQL text, so injection cannot happen no matter what the user types.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://localhost:5432/shop";
        String sql = "SELECT id FROM users WHERE name = ?";
        try (Connection conn = DriverManager.getConnection(url, "app", "secret");
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, "Ada");
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) System.out.println(rs.getInt("id"));
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

Binding Multiple Parameters

Each ? gets its own setter call. Order matters: parameter 1 is the first ?, parameter 2 the second, and so on.

Use the setter that matches the column type — setInt, setString, setDouble, setBoolean, and so on.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://localhost:5432/shop";
        String sql = "INSERT INTO users(name, age, active) VALUES (?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(url, "app", "secret");
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, "Grace");
            ps.setInt(2, 42);
            ps.setBoolean(3, true);
            int rows = ps.executeUpdate();
            System.out.println("Inserted " + rows + " row");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

Handling NULL

To bind a SQL NULL, use setNull(index, type) with a java.sql.Types constant.

Do not pass a Java null to setString and hope it works — be explicit:

  • ps.setNull(2, java.sql.Types.INTEGER)

Retrieving Generated Keys

After an INSERT you often need the auto-generated id.

Pass Statement.RETURN_GENERATED_KEYS when preparing, then read ps.getGeneratedKeys().

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://localhost:5432/shop";
        String sql = "INSERT INTO users(name) VALUES (?)";
        try (Connection conn = DriverManager.getConnection(url, "app", "secret");
             PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            ps.setString(1, "Linus");
            ps.executeUpdate();
            try (ResultSet keys = ps.getGeneratedKeys()) {
                if (keys.next()) System.out.println("New id: " + keys.getLong(1));
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

Batch Inserts

Inserting thousands of rows one statement at a time is slow. Use batching:

  • Bind parameters, then ps.addBatch().
  • Repeat for each row.
  • Call ps.executeBatch() once.

This sends the rows together, dramatically reducing round trips.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://localhost:5432/shop";
        String sql = "INSERT INTO tags(label) VALUES (?)";
        String[] labels = {"java", "jdbc", "sql"};
        try (Connection conn = DriverManager.getConnection(url, "app", "secret");
             PreparedStatement ps = conn.prepareStatement(sql)) {
            for (String label : labels) {
                ps.setString(1, label);
                ps.addBatch();
            }
            int[] counts = ps.executeBatch();
            System.out.println("Batched " + counts.length + " inserts");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

Reusing a Statement

A single PreparedStatement can be executed many times with different parameters.

Re-bind the placeholders and call execute again. The database reuses the cached execution plan, which is why prepared statements are faster for repeated queries.

Never Concatenate

The golden rule: any value that varies must be a ? parameter.

Only fixed, code-controlled identifiers (like a whitelisted column name) may be concatenated — and even then validate against an allowlist. User-supplied data is always bound, never concatenated.

Closing and Reuse Scope

A PreparedStatement is tied to its Connection and should be closed when done.

Inside try-with-resources, declare the statement so it closes before the connection. If you reuse a statement many times in a loop, prepare it once outside the loop and only re-bind parameters inside — re-preparing each iteration throws away the cached plan.

Quick Check

Why does a PreparedStatement prevent SQL injection?

Recap

You learned to write safe, fast queries:

  • Use ? placeholders and typed setters (1-based index).
  • Bind values with setString, setInt, setNull, etc.
  • Retrieve auto keys with RETURN_GENERATED_KEYS and getGeneratedKeys.
  • Batch many writes with addBatch + executeBatch.
  • Never concatenate user input into SQL.

Frequently asked questions

Is the “PreparedStatement” lesson free?

Yes — the full text of “PreparedStatement” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “PreparedStatement”?

Safe parameterized queries. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “PreparedStatement” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. JDBC Fundamentals
  2. PreparedStatement
  3. Transactions
  4. Connection Pooling with HikariCP
← Back to Java Academy