Statement Call in Java
Statement Call in Java
PreparedStatement
Once a parameter has been set with a value, it will retain that value until
it is reset to another value or the method clearParameters is called.
ps.clearParameters( );
ps.setString(1, “D4");
ps.executeQuery
For Efficiency
If the same SQL statement is executed many times with different
parameters, it is more efficient to use a PreparedStatement object. It will
normally reduce execution time.
Unlike a Statement object, it is given an SQL statement when it is created.
Statement Object
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery(“SELECT * FROM EMP WHERE
Dept_No=D1”);
PreparedStatement Object
PreparedStatement ps = con.prepareStatement ( “SELECT *
FROM EMP WHERE DeptNo=?”);
ResultSet rs = ps.executeQuery();
Contd..
The advantage to this is that in most cases, this SQL statement will be
sent to the DBMS right away, where it will be compiled.
As a result, the PreparedStatement object contains not just an SQL
statement, but an SQL statement that has been precompiled. This means
that when the PreparedStatement is executed, the DBMS can just run the
PreparedStatement's SQL statement without having to compile it first.
Stored Procedures
Stored procedures are essentially programs that we can write and are
internally executed by the database engine itself
These can be stored in database itself
Stored procedures in Java:
These are implemented using Java static methods
A Java class is written which contain one or more static methods
This class is wrapped in a JAR file and installed on the target database
This stored procedure is callable by Java
public class MyStoredProcedures{
public int getPrice(String carType) throws SQLException{
Connection con=DriverManager.getConnection(“jdbc:default:con”);
Statement stat = con.createStatement();
ResultSet rs= stat.executeQuery(“SELECT Price FROM CARDATA
WHERE CarType = ‘”+carType+”’”);
return rs.getInt(“Price”);
}
// other static methods
}
CallableStatement
Contd..