PreparedStatement Object


  • A PreparedStatement object holds precompiled SQL statements.
  • Use this object for statements you want to execute more than once.
  • A prepared statement can contain variables that you supply each time you execute the statement.
  • PreparedStatement is inherited from Statement; the difference is that a PreparedStatement holds precompiled SQL statements.
  • If you execute a Statement object many times, its SQL statement is compiled each time. PreparedStatement is more efficient because its SQL statement is compiled only once, when you first prepare the PreparedStatement. After that, each time you execute the SQL statement in the PreparedStatement, the SQL statement does not have to be recompiled.
  • Therefore, if you need to execute the same SQL statement several times within an application, it is more efficient to use PreparedStatement than Statement.
  • PreparedStatement Parameters.A PreparedStatement does not have to execute exactly the same query each time. You can specify parameters in the PreparedStatement SQL string and supply the actual values for these parameters when the statement is executed.

How to Create a Prepared Statement:

1.Register the driver and create the database connection.
2.Create the prepared statement, identifying variables with a question mark (?).

 

  PreparedStatement pstmt =
  conn.prepareStatement("update ACME_RENTALS
  set STATUS = ? where RENTAL_ID = ?");

  PreparedStatement pstmt =
  conn.prepareStatement("update ACME_RENTALS
  set STATUS = ? where RENTAL_ID = ?");
  pstmt.setString(1, "OUT");
  pstmt.setInt(2, rentalid);
  pstmt.executeUpdate();

Search: