Prepared Statements in JDBC

PreparedStatement is a special type of Statement which is used to execute parameterized query.

Benefits of using PreparedStatement :

  • PreparedStatement allows you to write dynamic and parametric query.
  • Easy to reuse the PreparedStatement with new parameter values.
  • Prepared statement is pre-compiled. When you use prepared statement(i.e pre-compiled statement), As soon as Database gets this statement, it compiles it and caches it so that it can use the last compiled statement for successive call of same statement. So it becomes pre-compiled for successive calls.
  • In case of PreparedStatement, Database use an already compiled and defined access plan, this allows prepared statement query to run faster than normal query.
  • Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Methods such as setString() automatically escape special characters such as quotations within the passed in SQL statement, preventing dangerous SQL injection attacks.
  • Enables Batch processing of Statements.

Let’s use PreparedStatement to insert records to the Student table by reusing the same PreparedStatement object.

DB Records before inserting new records

Screen Shot 2020-02-08 at 2.52.58 PM

Java Code 

Screen Shot 2020-02-08 at 5.53.23 PM


Screen Shot 2020-02-08 at 5.53.06 PM

DB Records now

Screen Shot 2020-02-08 at 5.53.44 PM

Batch Processing



Screen Shot 2020-02-08 at 6.41.34 PM

DB Records after Batch processing

Screen Shot 2020-02-08 at 6.42.22 PM

Leave a Reply

Your email address will not be published. Required fields are marked *