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
DB Records now
DB Records after Batch processing