The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
Example:
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.
Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.
The prepareStatement() method of Connection interface is used to return the object of PreparedStatement. Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}
PreparedStatement methods are:
package com.java.session.ninteen;
import java.sql.*;
public class PreparedStatementExample {
static final String DB_URL = "jdbc:mysql://localhost/emp";
static final String USER = "root";
static final String PASS = "PASSWORD";
static final String QUERY = "INSERT INTO EMP.EMPLOYEE VALUES(?,?,?,?)";
public static void main(String[] args) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = con.prepareStatement(QUERY);
pstmt.setInt(1, 14);
pstmt.setInt(2, 24);
pstmt.setString(3, "sadakhat");
pstmt.setString(4, "navab");
int result = pstmt.executeUpdate();
System.out.println(result + " record inserted");
} catch (SQLException se) {
se.printStackTrace();
} finally {
try {
pstmt.close();
con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}