|
The PreparedStatement interface inherits from Statement and differs from it in two ways:
1. The instances of PreparedStatement are already compiled so it is faster than the normal statements.
2. The parameters in the PreparedStatements are denoted by “?” and set at the runtime and we don’t have to convert any datatypes in the process. We just have to call the appropriate set method example setString() etc.
Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement. The three methods execute, executeQuery, and executeUpdate are modified so that they take no argument.
The following example will demonstrate the use of the prepared statements in the java applications.
package com.visualbuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class PreparedStatementExample {
public static void main(String[] args) {
try {
/** Loading the driver*/
Class.forName("com.mysql.jdbc.Driver");
/** Getting Connection*/
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
/** Creating Statement*/
PreparedStatement pst = con.prepareStatement("insert into visualbuilder(id,name)values(?,?)");
pst.setInt(1,1);
pst.setString(2,"VisualBuilder");
int i= pst.executeUpdate();
System.out.println(i + " Record(s) Inserted");
/** Closing the Connection*/
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:-
1 Recored(s) inserted |