Java Reference
In-Depth Information
71 String courseId = tfCourseId.getText();
72
try
{
73
preparedStatement.setString(
1
, ssn);
74
preparedStatement.setString(
2
, courseId);
75
ResultSet rset = preparedStatement.executeQuery();
execute statement
76
77
if
(rset.next()) {
78 String lastName = rset.getString(
1
);
79 String mi = rset.getString(
2
);
80 String firstName = rset.getString(
3
);
81 String title = rset.getString(
4
);
82 String grade = rset.getString(
5
);
83
84
// Display result in a label
85 lblStatus.setText(firstName +
" "
+ mi +
86
" "
+ lastName +
"'s grade on course "
+ title +
" is "
+
87 grade);
88 }
else
{
89 lblStatus.setText(
"Not found"
);
90 }
91 }
92
catch
(SQLException ex) {
93 ex.printStackTrace();
94 }
95 }
96 }
show result
This example does exactly the same thing as Listing 32.2 except that it uses the prepared
statement to dynamically set the parameters. The code in this example is almost the same as
in the preceding example. The new code is highlighted.
A prepared query string is defined in lines 56-59 with
ssn
and
courseId
as parameters.
An SQL prepared statement is obtained in line 62. Before executing the query, the actual
values of
ssn
and
courseId
are set to the parameters in lines 73-74. Line 75 executes the
prepared statement.
32.21
✓
✓
Describe prepared statements. How do you create instances of
PreparedStatement
? How do you execute a
PreparedStatement
? How do
you set parameter values in a
PreparedStatement
?
Check
Point
32.22
What are the benefits of using prepared statements?
CallableStatement
enables you to execute SQL stored procedures.
Key
Point
The
CallableStatement
interface is designed to execute SQL-stored procedures. The
procedures may have
IN
,
OUT
or
IN OUT
parameters. An
IN
parameter receives a value
passed to the procedure when it is called. An
OUT
parameter returns a value after the proce-
dure is completed, but it doesn't contain any value when the procedure is called. An
IN OUT
parameter contains a value passed to the procedure when it is called and returns a value after
it is completed. For example, the following procedure in Oracle PL/SQL has
IN
parameter
p1
,
OUT
parameter
p2
, and
IN OUT
parameter
p3
.
IN
parameter
OUT
parameter
IN OUT
parameter
create or replace procedure
sampleProcedure
(p1
in varchar
, p2
out number
, p3
in out integer
)
is
begin
/* do something */
end
sampleProcedure;
/
Search WWH ::
Custom Search