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
- import java.sql.*;
- public class PreparedInsert {
- public static void main(String[] args) {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- Connection conn= DriverManager.getConnection
- ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
- String query="insert into dietstudent values(?,?,?,?)";
- PreparedStatement ps=conn.prepareStatement(query);
- ps.setString(1, "14092"); //Enr_no
- ps.setString(2, "abc_comp"); //Name
- ps.setString(3, "computer"); //Branch
- ps.setString(4, "cx"); //Division
- int i=ps.executeUpdate();
- System.out.println("no. of rows updated ="+i);
- ps.close();
- conn.close();
- }
- catch(Exception e){System.out.println(e.toString());
- }
- }//PSVM
- }//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.