Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

JDBC · Lesson 4

Statement vs PreparedStatement

Choosing a JDBC Statement

JDBC offers Statement, PreparedStatement, and CallableStatement for sending SQL to a database. A PreparedStatement separates SQL structure from values, which improves safety and often lets the database reuse a query plan. The right choice makes database code easier to review and less vulnerable to injection.

Using PreparedStatement

Create placeholders with ? and bind values with typed setter methods. The database receives the SQL structure separately from user input.

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

public class CustomerLookup {
    public String findCustomerName(Connection connection, long customerId) throws Exception {
        String sql = "SELECT name FROM customers WHERE id = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setLong(1, customerId);
            try (ResultSet results = statement.executeQuery()) {
                return results.next() ? results.getString("name") : null;
            }
        }
    }
}

Statement Comparison

TypeParametersBest useMain concern
StatementNoneFixed administrative SQLInjection risk with concatenation
PreparedStatementTyped placeholdersUser input and repeated SQLMust bind every value
CallableStatementIN and OUT parametersStored proceduresDatabase-specific contracts

Common Mistake and Practices

Common Mistake: Building SQL with string concatenation from a request parameter. An input such as a crafted username can change the meaning of the SQL and expose data.

  • Prefer PreparedStatement for application queries.
  • Bind values with the matching setter type.
  • Keep SQL readable and parameterized.
  • Close statements with try-with-resources.
  • Check update counts when changing data.

Real-World Use Case

A customer search endpoint accepts a user-entered email address. A prepared statement safely binds that email and returns only the matching account without allowing the search text to become executable SQL.

Quiz Check

Quick Knowledge Test

Loading quiz questions...