What is Prepared statement (Parameterized Query)?

A SQL query must be compiled before DBMS process query.The compiling process can become expensive overhead if the query is executed several times by the same instance of of the J2ee component during the same session.A SQL query can be precompiled and executed by PreparedStatement Object.
•Prepared statement can execute the parameterized SQL statement which accepts value of the parameter at the time of execution of the statement.
•This is necessary when a SQL statement is characterized depending on some value or a criterion which is decided in run time.
•Used to execute queries need to be used repeatedly.
•First it foreward the query to sql engine, gets the id of the compiled query then use the id for next query executions.
•A prepared statement is prepared by using the prepareStatement () of connection and by providing the parameters represented by “ ? ” in the preparedStatement() along with the query.
•Set the parameter represented by ? is replaced by using setXXX() method of prepared statement. setXXX() needs two parameters. First question mark place holder and second is the value.
•According to type of the statement: use executeQuery() or executeUpdate().It does not requird any parameter because the query is already associated with the Preparedstatement.

Example:
import java.sql.*;
class demo
{
public static void main(String[] args){
Connection con=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
PreparedStatement ps=con.prepareStatement("insert into emp values(?,?,?)");
ps.setInt(1,5);
ps.setString(2,"bhabani");
ps.setString(3,"USA");
ps.execute();
con.commit();
System.out.println("data inserted successfully");
}catch(Exception e){
System.out.println("the exception is::::->"+e);
}
finally{
try{
con.close();}
catch(Exception e){
System.out.println("2nd try block exception:::->"+e);
}}}};

1 comment:

  1. good job...
    visit mine also
    http://periodicupdates.blogspot.com

    ReplyDelete