Skip to main content

PreparedStatement Interface

PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.

Let's see the example of parameterized query:

  1. String sql="insert into emp values(?,?,?)";  

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.


How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of PreparedStatement. Syntax:

  1. public PreparedStatement prepareStatement(String query)throws SQLException{}  

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

MethodDescription
public void setInt(int paramIndex, int value)sets the integer value to the given parameter index.
public void setString(int paramIndex, String value)sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value)sets the float value to the given parameter index.
public void setDouble(int paramIndex, double value)sets the double value to the given parameter index.
public int executeUpdate()executes the query. It is used for create, drop, insert, update, delete etc.
public ResultSet executeQuery()executes the select query. It returns an instance of ResultSet.

Example of PreparedStatement interface that inserts the record

First of all create table as given below:

  1. create table emp(id number(10),name varchar2(50));  

Now insert records in this table by the code given below:

  1. import java.sql.*;  
  2. class InsertPrepared{  
  3. public static void main(String args[]){  
  4. try{  
  5. Class.forName("oracle.jdbc.driver.OracleDriver");  
  6.   
  7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  8.   
  9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");  
  10. stmt.setInt(1,101);//1 specifies the first parameter in the query  
  11. stmt.setString(2,"Ratan");  
  12.   
  13. int i=stmt.executeUpdate();  
  14. System.out.println(i+" records inserted");  
  15.   
  16. con.close();  
  17.   
  18. }catch(Exception e){ System.out.println(e);}  
  19.   
  20. }  
  21. }  

Example of PreparedStatement interface that updates the record

  1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");  
  2. stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name  
  3. stmt.setInt(2,101);  
  4.   
  5. int i=stmt.executeUpdate();  
  6. System.out.println(i+" records updated");  

Example of PreparedStatement interface that deletes the record

  1. PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");  
  2. stmt.setInt(1,101);  
  3.   
  4. int i=stmt.executeUpdate();  
  5. System.out.println(i+" records deleted");  

Example of PreparedStatement interface that retrieve the records of a table

  1. PreparedStatement stmt=con.prepareStatement("select * from emp");  
  2. ResultSet rs=stmt.executeQuery();  
  3. while(rs.next()){  
  4. System.out.println(rs.getInt(1)+" "+rs.getString(2));  
  5. }  


Example of PreparedStatement to insert records until user press n

  1. import java.sql.*;  
  2. import java.io.*;  
  3. class RS{  
  4. public static void main(String args[])throws Exception{  
  5. Class.forName("oracle.jdbc.driver.OracleDriver");  
  6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  7.   
  8. PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");  
  9.   
  10. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  11.   
  12. do{  
  13. System.out.println("enter id:");  
  14. int id=Integer.parseInt(br.readLine());  
  15. System.out.println("enter name:");  
  16. String name=br.readLine();  
  17. System.out.println("enter salary:");  
  18. float salary=Float.parseFloat(br.readLine());  
  19.   
  20. ps.setInt(1,id);  
  21. ps.setString(2,name);  
  22. ps.setFloat(3,salary);  
  23. int i=ps.executeUpdate();  
  24. System.out.println(i+" records affected");  
  25.   
  26. System.out.println("Do you want to continue: y/n");  
  27. String s=br.readLine();  
  28. if(s.startsWith("n")){  
  29. break;  
  30. }  
  31. }while(true);  
  32.   
  33. con.close();  
  34. }}  


Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&