java – What is the difference between Statement and PreparedStatement?

Question:

When I paid for the database chair, we worked only with the bank, alone, without any connection with an application that interacted externally with the DBMS.
Only then was JDBC (Java Database Connectivity) introduced to us. But due to the rush of the course, I learned about JDBC only enough to deal with the database.

So I have the following doubt:

What is the difference between the Statement and the PreparedStatement and when should I use one or the other?

Answer:

The difference goes beyond just adding parameters.

Most relational databases dealing with a query (query) JDBC / SQL in four steps:

  1. Interpret ( parse ) the SQL query;
  2. Compile the SQL query;
  3. Plan and optimize the data search path;
  4. Run the optimized query, fetching and returning data.

A Statement will always go through the four steps above for each SQL query sent to the database.

A Prepared Statement pre-executes steps (1) to (3). So, when creating a Prepared Statement some pre-optimization is done right away. The effect of this is that, if you intend to run the same query over and over again changing only the parameters of each one, execution using Prepared Statements will be faster and with less load on the database.

Another advantage of Prepared Statements is that, if used correctly, they help to avoid SQL Injection attacks. Note that for this, the query parameters must be assigned through the setInt() , setString() , etc. methods. present in the PreparedStatement interface and not by string concatenation.

For a query that will be executed a few times and does not require any parameters, Statement enough. For all other cases, prefer PreparedStatement .

(Based on this answer in English and at https://en.wikipedia.org/wiki/Prepared_statement ).

Scroll to Top