Java Reference
In-Depth Information
+ rs.getString(3) +
" - " + rs.getString(4));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
First, you can see that the
Connection
object is used to instantiate a
Pre-
paredStatement
object. The SQL string is passed to the
PreparedStatement
object's constructor on creation. Since the
PreparedStatement
is instantiated
within the
try-with-resources
construct, it will be automatically closed when it
is no longer in use. Next, the
PreparedStatement
object is used to set values for
any substitution variables that have been placed into the SQL string. As you can see,
the
PreparedStatement setString()
method is used in the example to set
the substitution variable at position 1 equal to the contents of the
recipeNumber
variable. The positioning of the substitution variable is associated with the placement
of the question mark (
?
) within the SQL string. The first question mark within the
string is assigned to the first position, the second one is assigned to the second position,
and so forth. If there were more than one substitution variable to be assigned, there
would be more than one call against the
PreparedStatement
, assigning each of
the variables until each one has been accounted for.
PreparedStatement
s can ac-
cept substitution variables of many different data types. For instance, if an
int
value
were being assigned to a substitution variable, a call to the
setInt(position,
variable)
method would be in order. See the online documentation or your IDE's
code completion for a complete set of methods that can be used for assigning substitu-
tion variables using
PreparedStatement
objects.
Once all the variables have been assigned, the SQL string can be executed. The
PreparedStatement
object contains an
executeQuery()
method that is used
to execute a SQL string that represents a query. The
executeQuery()
method re-
turns a
ResultSet
object, which contains the results that have been fetched from the
database for the particular SQL query. Next, the
ResultSet
can be traversed to ob-
tain the values retrieved from the database. Again, positional assignments are used to
retrieve the results by calling the
ResultSet
object's corresponding getter methods
and passing the position of the column value that you want to obtain. The position is
determined by the order in which the column names appear within the SQL string. In
the example, the first position corresponds to the
RECIPE_NUMBER
column, the
second corresponds to the
RECIPE_NAME
column, and so forth. If the
recipeNum-