2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

What is the difference between Statement and PreparedStatement

What is the difference between Statement and PreparedStatement
userimage

Overall definitions,

  • Statement is static and prepared statment is dynamic.
  • Statement is suitable for DDL and prepared statment for DML.
  • Statement is slower while prepared statement is faster.

And some additional benefits of using PreparedStatement over Statement,

  • PreparedStatement helps us in preventing SQL injection attacks because it automatically escapes the special characters.
  • PreparedStatement allows us to execute dynamic queries with parameter inputs.
  • PreparedStatement provides different types of setter methods to set the input parameters for the query.
  • PreparedStatement is faster than Statement. It becomes more visible when we reuse the PreparedStatement or use it’s batch processing methods for executing multiple queries.
  • PreparedStatement helps us in writing object Oriented code with setter methods whereas with Statement we have to use String Concatenation to create the query. If there are multiple parameters to set, writing Query using String concatenation looks very ugly and error prone.
  • PreparedStatement returns FORWARD_ONLY ResultSet, so we can only move in forward direction.
  • Unlike Java Arrays or List, the indexing of PreparedStatement variables starts with 1.
  • One of the limitation of PreparedStatement is that we can’t use it for SQL queries with IN clause because PreparedStatement doesn’t allow us to bind multiple values for single placeholder (?).
userimage

This statement is one of features of the database system in which same SQL statement executes repeatedly with high efficiency. The prepared statements are one kind of the Template and used by application with different parameters.


  • The statement template is prepared and sent to the database system and database system perform parsing, compiling and optimization on this template and store without executing it.


  • Some of parameter like, where clause is not passed during template creation later application, send these parameters to the database system and database system use template of SQL Statement and executes as per request.


Prepared statements are very useful against SQL Injection because the application can prepare parameter using different techniques and protocols.


  • When the number of data is increasing and indexes are changing frequently at that time Prepared Statements might be fail because in this situation require a new query plan.
Answer is