- It is an interface.
- It is a sub-type of Statement.
- It is implemented by JDBC driver developers.
- An object that represents a pre-compiled SQL statements.
- A SQL statement is pre-compiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.
- PreparedStatement allows SQL statement with parameters.
How to create PreparedStatement object
Connection provide the following method which return PreparedStatement object.
- PreparedStatement prepareStatement(String sql) - creates a PreparedStatement object for sending parameterized SQL statements to the database.
- Example - PreparedStatement ps = con.prepareStatement(select * from emp);
What is the difference between Statement and PreparedStatement
- A standard Statement is used to create java representation of a literal SQL statement and execute it on the database, A PreparedStatement is a pre-compiled 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 PreparedStatement has to verify its metadata against the database only once.
- If we want to execute the SQL statement once then we should go for Statement, If we want to execute a single SQL statement multiple number of times, then we should go for PreparedStatement. PreparedStatement objects can be reused with passing different values to the queries.
How to define Parameters
- Parameter is a place-holder which receive value after compiling SQL statement.
- Each parameter is represented using a special symbol " ? ".
- It is identified with index number.
- This index number starts with 1.
- PreparedStatement provides setter methods to define the value of each parameter.
- For each datatype it provide one setter method.
PreparedStatement provides the following methods -
- void setInt(int paramIndex, int value);
- void setFloat(int paramIndex, float value);
- void setDouble(int paramIndex, double value);
- void setString(int paramIndex, String value);
No comments:
Post a Comment