Wednesday, 30 March 2016

What is PreparedStatement and how it is different from Statement ?


A prepared statement is an SQL statement that is pre-compiled by the database.
Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements).

Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.

Example
PreparedStatement pstmt = 
  connection.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00);
pstmt.setInt(2, 110592);


Statement vs. PreparedStatement
  • Statement is used to create a Java representation of a literal SQL statement and execute it on the database.
  • A PreparedStatement is a precompiled statement.
    This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first.
  • Statement has to verify its metadata against the database every time.
  • While a prepared statement has to verify its metadata against the database only once.
  • If you want to execute the SQL statement once go for Statement.
  • If you want to execute a single SQL statement multiple number of times, then go for PreparedStatement.
  • PreparedStatement objects can be reused with passing different values to the queries. 

No comments:

Post a Comment

Note: only a member of this blog may post a comment.