Vous êtes sur la page 1sur 17

Statements

PreparedStatement

 A prepared statement is an SQL statement with parameters that can


change at any time.
 Instances of PreparedStatement contain an SQL statement that has
already been compiled. This is what makes a statement "prepared."
 Used for complex queries or repeated queries i.e. for convenience or
efficiency.
Contd..

 Being a subclass of Statement, PreparedStatement inherits all the


functionality of Statement.
 Also, the methods executeQuery, and executeUpdate are modified so
that they take no argument. The Statement forms of these methods (the
forms that take an SQL statement parameter) should never be used with
a PreparedStatement object.
 prepareStatement method
public PreparedStatement prepareStatement(String sql) throws
SQLException
 Creates a PreparedStatement object for sending parameterized SQL

statements to the database.


For Convenience

 The advantage of using SQL statements that take parameters is that


we can use the same statement and supply it with different values
each time it is executed
 The SQL statement contained in a PreparedStatement object may
have one or more IN parameters.
 An IN parameter is a parameter whose value is not specified when the
SQL statement is created. Instead, the statement has a question mark
("?") as a placeholder for each IN parameter.
 The "?" is also known as a parameter marker. An application must set
a value for each question mark in a prepared statement before
executing the prepared statement
Contd..
An example of JDBC prepared statement
PreparedStatement ps = con.prepareStatement(SELECT Name,Salary FROM
EMP WHERE Dept_No=?”);
 This creates an statement which is ready to be executed
 To execute the query, the values of the positional parameter placemarked by
the “?” symbols are specified
 Parameter numbers start from 1 and not 0.
 We need to use set<type>() method to do this, where the type depends on the
data type of the column
ps.setString(1, “D1”);
 After supplying values for all positional parameters, we can execute query:
ResultSet rs=ps.executeQuery( );
Contd..
 You can often make coding easier by using a for loop or a while loop to set
values for input parameters.
 PreparedStatement ps;
 String pstmt = “SELECT Name,Salary FROM EMP WHERE
Dept_No=?”;
 ps= con.prepareStatement(pstmt);
 String [ ] dept = {“D1", “D2", “D3"};
 int len =dept.length;
 for(int i = 0; i < len; i++) {
ps.setString(1, dept[i]);
ps.executeQuery();
}
Contd..

 To set an integer value to NULL, use call:


ps.setNull(1, Types.INTEGER);
 The Types class contains constants that represent the various SQL data
types supported by JDBC

 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

 A CallableStatement object provides a way to call stored procedures in a


standard way for all RDBMSs.
CallableStatement cstmt = con.prepareCall(String sql);
prepareCall method
public CallableStatement prepareCall(String sql) throws SQLException
 Creates a CallableStatement object for calling database stored
procedures
 A stored procedure is stored in a database; the call to the stored
procedure is what a CallableStatement object contains.
Contd..

 This call may take one of two forms:


 with a result parameter,

 without result parameter.

 A result parameter, a kind of OUT parameter, is the return


value for the stored procedure.
 Both forms may have a variable number of parameters used for input
(IN parameters), output (OUT parameters), or both (INOUT
parameters). A question mark serves as a placeholder for a parameter.
Syntax

 The syntax for invoking a stored procedure


{call procedure_name[(?, ?, ...)]}
 the square brackets indicate optional part
 The syntax for a procedure that returns a result parameter is:
{? = call procedure_name[(?, ?, ...)]}
 The syntax for a stored procedure with no parameters would look like
this:
{call procedure_name}
Contd..

 The value of each IN parameter is set by calling a set<type>() method,


while each OUT parameter or INOUT parameter should be registered by
calling a registerOutParameter method.
 Method for registering output parameters:
public void registerOutParameter(int whichParameter, int sqlType)
Example

String callString = "{?=call getPrice(?)}" ;


CallableStatement cs = connection.prepareCall(callString);
cs.setString(1, “Scorpio");
cs.execute();
System.out.println(cs.getString(2));

 
 
Contd..

 Before creating a CallableStatement object one must know the DBMS


being used supports stored procedures or not if yes then what those
procedures are.
 To check this, the DatabaseMetaData method
supportsStoredProcedures() will return true if the DBMS supports stored
procedure calls, and the method getProcedures() will return a
description of the stored procedures available.

Vous aimerez peut-être aussi