HuntExams Academy logo
JavaBeginner#jdbc

What is the difference between Statement and PreparedStatement?

Answer

Statement executes raw SQL strings and is vulnerable to SQL injection when concatenating user input. PreparedStatement precompiles parameterized SQL, improving performance for repeated execution and preventing SQL injection via safe parameter binding.

Example

PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
ps.setInt(1, userId);
ResultSet rs = ps.executeQuery();

Detailed explanation

Statement and PreparedStatement are JDBC interfaces used to execute SQL through a database connection. PreparedStatement extends Statement, but their main difference is how SQL and input values are supplied. With Statement, you pass a complete SQL string to an execution method, such as statement.executeQuery(sql). With PreparedStatement, you provide a SQL template to connection.prepareStatement(sql), bind values to question-mark placeholders, and then call executeQuery() or executeUpdate() without passing the SQL again. Both support queries and data changes; neither automatically commits or rolls back a transaction independently of the connection settings.

The most important difference is safe handling of input. If you concatenate user input into a Statement query, an attacker may supply text that changes the query's meaning. PreparedStatement separates the SQL structure from parameter values: the JDBC driver handles each bound value as data rather than executable SQL syntax. For example, in SELECT * FROM users WHERE id = ?, ps.setInt(1, userId) binds an integer to the first placeholder. Parameter indexes start at 1, not 0. This protection applies to bound values; concatenating untrusted text into the SQL template can still introduce injection vulnerabilities.

PreparedStatement is also designed for reuse. You can prepare a query once, change its parameter values, and execute it repeatedly, or add multiple parameter sets to a batch. Depending on the JDBC driver, database, and configuration, preparation and execution-plan reuse can reduce repeated parsing and planning work. However, calling prepareStatement does not guarantee immediate server-side compilation or better performance for every query. Some drivers defer preparation or emulate it on the client, so performance claims should be qualified rather than presented as universal rules.

In practice, prefer PreparedStatement for queries containing variable values because it improves security, readability, and type handling through methods such as setInt and setString. Statement can be adequate for fixed SQL without external input. Placeholders represent values, not table names, column names, or SQL keywords; dynamic identifiers require strict allowlisting. Close statements and result sets with try-with-resources. Interviewers usually expect you to explain parameter binding, demonstrate the execution syntax, and distinguish reliable security benefits from database-dependent performance benefits.

Key points to remember

  • Statement receives complete SQL at execution time; PreparedStatement receives a template before execution.
  • Bound parameters are treated as data, preventing injection through those values.
  • Parameter indexes start at 1, with typed setters such as setInt and setString.
  • PreparedStatement supports repeated execution and batching; preparation benefits depend on the driver and database.
  • Placeholders cannot replace SQL identifiers, and both interfaces require proper resource cleanup.

Common mistakes candidates make

  • Claiming Statement is inherently unsafe even when executing fixed SQL with no untrusted input.
  • Assuming PreparedStatement is always faster or always compiled immediately on the database server.
  • Concatenating user input into a PreparedStatement template and assuming its name guarantees injection protection.

Likely follow-up questions

Can I use a placeholder for a table name or sorting direction?

No; placeholders bind values, not identifiers or keywords such as ASC and DESC. Map permitted user choices to predefined SQL fragments using a strict allowlist.

What is the difference between executeQuery() and executeUpdate()?

Use executeQuery() for SQL that returns a ResultSet, typically SELECT. Use executeUpdate() for INSERT, UPDATE, DELETE, or statements that return no result set; it returns an update count or zero when applicable.

How do you reuse a PreparedStatement?

Create it once and set the parameters before each execution, or call addBatch() for each parameter set followed by executeBatch(). Existing parameter values remain until replaced or cleared, so explicitly set every required value for each iteration.

Interview tip: Lead with SQL construction and safe parameter binding, explain the given example, and qualify the performance benefit as driver- and database-dependent.

Related Interview Questions

1
JavaIntermediate#jdbc

What is a CallableStatement used for?

Open
2
JavaIntermediate#jdbc

What is connection pooling and why is it important?

Open
3
JavaIntermediate#jdbc

How do you manage transactions manually in JDBC?

Open