PreparedStatement
The PreparedStatement interface is a sub interface of Statement. It is used to execute parameterized query.The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.
String sql="insert into emp values(?,?,?)";
(?) values will be set by calling the setter methods of PreparedStatement.
Method | Description |
---|---|
public void setInt(int index,int value) | sets integer value to the given parameter index. |
public void setString(int index, String val) | sets String value to the given parameter index. |
public void setFloat(int index, float value) | sets float value to the given parameter index. |
public void setDouble(int index, double val) | sets double value to the given parameter index. |
public int executeUpdate() | Uses for create, drop, insert, update, delete queries |
public ResultSet executeQuery() | Executes the select query. |
Boolean execute() | It returns TRUE for SELECT queries, FALSE for update, delete Queries |
void addBatch() | |
ParameterMetaData getParameterMetaData() | Retrieves the number, types and properties of this PreparedStatement object’s parameters |
ResultSetMetaData getMetaData() | contains information about the columns of the ResultSet object |
void setBlob(int index, Blob x) | Inserts Binary Large Object Videos,Audios |
void setBlob(int index,InputStream is) | |
void setBinaryStream(int i,InputStream is) | |
getBinarayStream(-column”); | |
void setClob(int index, Clob x) | Inserts character Large Object Files |
void setClob(int index, Reader reader) | |
getCharacterStream(-column”); |
Statement vs PreparedStatement
java.sql.Statement | java.sql.PreparedStatement |
---|---|
Statement is used for executing a static SQL statement in java JDBC. | PreparedStatement is used for executing a precompiled SQL statement in java JDBC. |
java.sql.Statement cannot accept parameters at runtime in java JDBC. | java.sql.PreparedStatement can be executed repeatedly, it can accept different parameters at runtime in java JDBC. |
java.sql.Statement is slower as compared to PreparedStatement in java JDBC. | java.sql.PreparedStatement is faster because it is used for executing precompiled SQL statement in java JDBC. |
public class JDBC {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/mydb";
String u = "root";
String p = "123456";
PreparedStatement ps=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, u, p);
ps = con.prepareStatement("insert into customer values(?,?,?)");
ps.setInt(1, 143);
ps.setString(2, "sri");
ps.setString(3, "mum");
int res = ps.executeUpdate();
System.out.println("Result : " + res);
ps =con.prepareStatement("SELECT * FROM customer c WHERE c.cid<? ");
ps.setInt(1, 200);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(2));
}
}
}
Result : 1
Ram
RAKESH
Surya
sri
PREVIOUSCURD Operations
NEXTBLOB