statement call in java
TRANSCRIPT
-
8/9/2019 Statement call in java
1/17
Statements
-
8/9/2019 Statement call in java
2/17
PreparedStatement
A prepared statement is an SQL statement with parameters
that can change at any time.
Instances of PreparedStatement contain an SQL statement thathas already been compiled. This is what makes a statement
"prepared."
Used for complex queries or repeated queries i.e. for
convenience or efficiency.
-
8/9/2019 Statement call in java
3/17
Contd..
Being a subclass ofStatement,PreparedStatement inherits all thefunctionality ofStatement.
Also, the methods executeQuery, and executeUpdate are modified sothat they take no argument. The Statement forms of these methods (the
forms that take an SQL statement parameter) should neverbe used with
a PreparedStatement object.
prepareStatement method
public PreparedStatement prepareStatement(String sql) throwsSQLException
Creates a PreparedStatement object forsending parameterized
SQL statements to the database.
-
8/9/2019 Statement call in java
4/17
ForConvenience
The advantage ofusing 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 ormore IN parameters.
An IN parameteris a parameterwhose value is not specified when the
SQL statement is created. Instead, the statement has a question mark
("?") as a placeholderforeach IN parameter.
The "?" is also known as a parametermarker. An application must set
a value foreach question mark in a prepared statement before
executing the prepared statement
-
8/9/2019 Statement call in java
5/17
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 parameterplacemarked by the ? symbols are specified
Parameter numbers start from 1 and not 0.
We need to use set() method to do this, where the type
depends on the data type of the columnps.setString(1, D1);
After supplying values for all positional parameters, we canexecute query:
ResultSet rs=ps.executeQuery( );
-
8/9/2019 Statement call in java
6/17
Contd..
You can often make coding easier by using a for loop or a whileloop to set values for input parameters.
PreparedStatement ps;
String pstmt = SELECT Name,Salary FROM EMPWHERE
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();
}
-
8/9/2019 Statement call in java
7/17
Contd..
To set an integer value to NULL, use call:
ps.setNull(1, Types.INTEGER);
The Types class contains constants that represent the variousSQL data types supported by JDBC
Once a parameter has been set with a value, it will retain thatvalue until it is reset to another value or the method
clearParameters is called.ps.clearParameters( );
ps.setString(1, D4");
ps.executeQuery
-
8/9/2019 Statement call in java
8/17
ForEfficiency
If the same SQL statement is executed many times with differentparameters, it is more efficient to use a PreparedStatementobject. It will normally reduce execution time.
Unlike a Statement object, it is given an SQL statement when it iscreated.
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();
-
8/9/2019 Statement call in java
9/17
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 SQLstatement, 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 havingto compile it first.
-
8/9/2019 Statement call in java
10/17
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 ormore static methods
This class is wrapped in a JARfile and installed on the target database
This stored procedure is callable by Java
-
8/9/2019 Statement call in java
11/17
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 FROMCARDATA
WHERE CarType = +carType+);
return rs.getInt(Price);
}
//otherstatic methods
}
-
8/9/2019 Statement call in java
12/17
CallableStatement
A CallableStatement object provides a way to call stored procedures in
a standard way forall RDBMSs.
CallableStatement cstmt = con.prepareCall(String sql);prepareCall method
public CallableStatement prepareCall(String sql) throws
SQLException
Creates a CallableStatement object forcalling database stored
procedures A stored procedure is stored in a database; the call to the stored
procedure is what a CallableStatement object contains.
-
8/9/2019 Statement call in java
13/17
Contd..
This call may take one of twoforms:
with a result parameter,
without result parameter.
Aresult parameter, a kind ofOUT parameter, is the return
value forthe stored procedure.
Both forms may have a variable numberofparameters used forinput (IN
parameters),output (OUT parameters),orboth (INOUT parameters). Aquestion mark serves as a placeholderfora parameter.
-
8/9/2019 Statement call in java
14/17
Syntax
The syntax forinvoking 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}
-
8/9/2019 Statement call in java
15/17
Contd..
The value of each IN parameter is set by calling a set()
method, while each OUT parameter or INOUT parameter should
be registered by calling a registerOutParametermethod. Method for registering output parameters:
public void registerOutParameter(int whichParameter, int sqlType)
-
8/9/2019 Statement call in java
16/17
Example
String callString = "{?=call getPrice(?)}" ;
CallableStatement cs = connection.prepareCall(callString);
cs.setString(1, Scorpio");cs.execute();
System.out.println(cs.getString(2));
-
8/9/2019 Statement call in java
17/17
Contd..
Before creating a CallableStatement object one must know the DBMS
being used supports stored procedures ornot ifyes then what those
procedures are. To check this, the DatabaseMetaData method
supportsStoredProcedures() will return true if the DBMS supportsstored procedure calls, and the method getProcedures() will return a
description of the stored procedures available.