Advanced Java (2160707)

BE | Semester-4   Winter-2018 | 20-11-2018

Q3) (c)

Explain the use of the PreparedStatement object of the JDBC with an appropriate example

Prepared Statement

  • The PreparedStatement interface extends the Statement interface.
  • It represents a precompiled SQL statement.
  • A SQL statement is precompiled and stored in a Prepared Statement object.
  • This object can then be used to efficiently execute this statement multiple times.

Methods Of Prepared Statement

Sr Method Description
1 public void setInt(int paramIndex, int value) Sets the integer value to the given parameter index.
2 public void setString(int paramIndex, String value) Sets the String value to the given parameter index.
3 public void setFloat(int paramIndex, float value) Sets the float value to the given parameter index.
4 public void setDouble(int paramIndex, double value) Sets the double value to the given parameter index.
5 public int executeUpdate() Executes the query. It is used for create, drop, insert, update, delete etc.
6 public ResultSet executeQuery() Executes the select query. It returns an instance of ResultSet.

Program

  1. import java.sql.*;
  2. public class PreparedInsert {
  3. public static void main(String[] args) {
  4. try {
  5. Class.forName("com.mysql.jdbc.Driver");
  6. Connection conn= DriverManager.getConnection
  7. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
  8. String query="insert into dietstudent values(?,?,?,?)";
  9. PreparedStatement ps=conn.prepareStatement(query);
  10. ps.setString(1, "14092"); //Enr_no
  11. ps.setString(2, "abc_comp"); //Name
  12. ps.setString(3, "computer"); //Branch
  13. ps.setString(4, "cx"); //Division
  14. int i=ps.executeUpdate();
  15. System.out.println("no. of rows updated ="+i);
  16. ps.close();
  17. conn.close();
  18. }
  19. catch(Exception e){System.out.println(e.toString());
  20. }
  21. }//PSVM
  22. }//class

Why To Use Prepared Statement

  • Improves performance:
  • The performance of the application will be faster, if you use PreparedStatement interface because query is compiled only once.
  • This is because creating a PreparedStatement object by explicitly giving the SQL statement causes the statement to be precompiled within the database immediately.
  • Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile the SQL statement.
  • Late binding and compilation is done by DBMS.
  • Provides the programmatic approach to set the values.