The difference goes beyond simply adding parameters.
Most relational databases handle a JDBC / SQL query in four steps:
Interpret ( parse ) the SQL query;
Compile the SQL query;
Plan and optimize the data search path;
Run the optimized query, fetching and returning the data.
A Statement will always go through the four steps above for each SQL query sent to the bank.
A Prepared Statement pre-executes steps (1) through (3). So when creating a Prepared Statement some pre-optimization is done right away. The effect of this is that if you plan to run the same query over and over again by changing only the parameters of each, running Prepared Statements will be faster and with less load on the database.
Another advantage of Prepared Statements is that, if used correctly, they help prevent SQL Injection attacks. Note that this requires the parameters of the query to be assigned through the methods setInt()
, setString()
, etc. present in the interface PreparedStatement
and not by concatenation of strings.
For a query that will be executed a few times and does not require any parameters, Statement
is enough. For other cases, prefer PreparedStatement
.
(Based on in this answer in link ).