Java Reference
In-Depth Information
ber
string variable was equal to
"13-1",
the results of executing the query in the ex-
ample would look something like the following:
13-1: Connecting to a Database - DriverManager and
DataSource Implementations
Of course, if the substitution variable is not set correctly or if there is an issue with
the SQL string, an exception will be thrown. This would cause the code that is con-
tained within the
catch
block to be executed. You should also be sure to clean up
after using
PreparedStatement
s by closing the statement when you are finished
using it. If you're not using a
try-with-resources
construct, it is a good practice
to put all the cleanup code within a
finally
block to be sure that the
Pre-
paredStatement
is closed properly even if an exception is thrown. In the example,
the
finally
block looks like the following
:
finally {
if (pstmt != null){
try {
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
You can see that the
PreparedStatement
object that was instantiated,
pstmt
,
is checked to see whether it is
NULL
. If not, it is closed by calling the
close()
meth-
od.
Working through the code in the solution to this recipe, you can see that similar
code is used to process database
INSERT
,
Update
, and
DELETE
statements. The
only difference in those cases is that the
PreparedStatement executeUp-
date()
method is called rather than the
executeQuery()
method. The
ex-
ecuteUpdate()
method will return an
int
value representing the number of rows
affected by the SQL statement.
The use of
PreparedStatement
objects is preferred over JDBC
Statement
objects. This is due to the fact that they are more secure and perform better. They can
also make your code easier to follow and maintain.