Java Reference
In-Depth Information
PreparedStatement
enables you to create parameterized SQL statements.
Key
Point
Once a connection to a particular database is established, it can be used to send SQL statements
from your program to the database. The
Statement
interface is used to execute static SQL
statements that don't contain any parameters. The
PreparedStatement
interface, extend-
ing
Statement
, is used to execute a precompiled SQL statement with or without parameters.
Since the SQL statements are precompiled, they are efficient for repeated executions.
A
PreparedStatement
object is created using the
prepareStatement
method in the
Connection
interface. For example, the following code creates a
PreparedStatement
for
an SQL
insert
statement:
PreparedStatement preparedStatement = connection.prepareStatement
(
"insert into Student (firstName, mi, lastName) "
+
"values (?, ?, ?)"
);
This
insert
statement has three question marks as placeholders for parameters representing
values for
firstName
,
mi
, and
lastName
in a record of the
Student
table.
As a subinterface of
Statement
, the
PreparedStatement
interface inherits all the
methods defined in
Statement
. It also provides the methods for setting parameters in the
object of
PreparedStatement
. These methods are used to set the values for the parameters
before executing statements or procedures. In general, the setter methods have the following
name and signature:
set
X
(
int
parameterIndex,
X
value);
where
X
is the type of the parameter, and
parameterIndex
is the index of the parameter
in the statement. The index starts from
1
. For example, the method
setString(int
parameterIndex, String value)
sets a
String
value to the specified parameter.
The following statements pass the parameters
"Jack"
,
"A"
, and
"Ryan"
to the placehold-
ers for
firstName
,
mi
, and
lastName
in
preparedStatement
:
preparedStatement.setString(
1
,
"Jack"
);
preparedStatement.setString(
2
,
"A"
);
preparedStatement.setString(
3
,
"Ryan"
);
After setting the parameters, you can execute the prepared statement by invoking
executeQuery()
for a SELECT statement and
executeUpdate()
for a DDL or update
statement.
The
executeQuery()
and
executeUpdate()
methods are similar to the ones defined
in the
Statement
interface except that they don't have any parameters, because the SQL
statements are already specified in the
prepareStatement
method when the object of
PreparedStatement
is created.
Using a prepared SQL statement, Listing 32.2 can be improved as in Listing 32.3.
L
ISTING
32.3
FindGradeUsingPreparedStatement.java
1
import
javafx.application.Application;
2
import
javafx.scene.Scene;
3
import
javafx.scene.control.Button;
4
import
javafx.scene.control.Label;
5
import
javafx.scene.control.TextField;
6
import
javafx.scene.layout.HBox;
7
import
javafx.scene.layout.VBox;
8
import
javafx.stage.Stage;
9
import
java.sql.*;
10
Search WWH ::
Custom Search