JDBC PreparedStatement interface

The JDBC PreparedStatement is used to execute parameterized queries against the database. PreparedStatement is an interface which provides the methods to execute parameterized queries. A parameter is represented by ? symbol in JDBC. PreparedStatement extends the Statement interface. We can get a PreparedStatement object by invoking the prepareStatement() method of Connection interface.
Syntax: PreparedStatement pstmt = conn.prepareStatement(SQL);

Advantages of PreparedStatement:

  1. 1. Parameterized query: Provides the facility of parameterized query.
  2. 2. Reusable: PreparedStatement can be easily used with new parameters.
  3. 3. Performance: It increases the performance because of database statement caching.

Difference between Statement and PreparedStatement in jdbc:

StatementPreparedStatement
  1. 1. Statement not executes the parameterized query.
  2. 2. Relational DB uses following 4 step to execute a query:
    a. Parse the query.
    b. Compile the query.
    c. Optimize/Plan the query.
    d. Execute the query.
    A statement always executes the all four steps.
  3. 3. No database statement caching in case of statement.
  1. 1. PreparedStatement can execute the parameterized query.
  2. 2. Relational DB uses following 4 step to execute a query:
    a. Parse the query.
    b. Compile the query.
    c. Optimize/Plan the query.
    d. Execute the query.
    PreparedStatement pre-executes first three steps in the execution.
  3. 3. It provides the database statement caching the execution plans of previously executed statements. Hence database engine can reuse the plans for statements that have been executed previously.

JDBC PreparedStatement examples:

No comments: