Java Reference
In-Depth Information
The main difference between performing a query using JDBC and using data ma-
nipulation language (DML) is that you will call different methods on the
Statement
object, depending on which operation you want to perform. To perform a query, you
need to call the
Statement executeQuery()
method. In order to perform DML
tasks such as insert, update, and delete, call the
executeUpdate()
method.
The
performCreate()
method in the solution to this recipe demonstrates the
operation of inserting a record into a database. To insert a record in the database, con-
struct a SQL
INSERT
statement in string format. To perform the insert, pass the SQL
string to the
Statement
object's
executeUpdate()
method. If the
INSERT
is
performed, an
int
value will be returned that specifies the number of rows that have
been inserted. If the
INSERT
operation is not performed successfully, either a zero will
be returned or a
SQLException
will be thrown, indicating a problem with the state-
ment or database connection.
The
performRead()
method in the solution to this recipe demonstrates the op-
eration of querying the database. To execute a query, call the
Statement
object's
executeQuery()
method, passing a SQL statement in string format. The result will
be a
ResultSet
object, which can then be used to work with the returned data. For
more information on performing queries, see Recipe 13-3.
The
performUpdate()
method in the solution to this recipe demonstrates the
operation of updating record(s) within a database table. First, construct a SQL
UPDATE
statement in string format. Next, to perform the update operation pass the SQL string to
the
Statement
object's
executeUpdate()
method. If the
UPDATE
is success-
fully performed, an
int
value will be returned, which specifies the number of records
that were updated. If the
UPDATE
operation is not performed successfully, either a zero
will be returned or a
SQLException
will be thrown, indicating a problem with the
statement or database connection.
The last database operation that needs to be covered is the
DELETE
operation. The
performDelete()
method in the solution to this recipe demonstrates the operation
of deleting record(s) from the database. First, construct n SQL
DELETE
statement in
string format. Next, to execute the deletion, pass the SQL string to the
Statement
object's
executeUpdate()
method. If the deletion is successful, an
int
value spe-
cifying the number of rows deleted will be returned. Otherwise, if the deletion fails, a
zero will be returned or a
SQLException
will be thrown, indicating a problem with
the statement or database connection.
Almost every database application uses at least one of the CRUD operations at
some point. This is foundational JDBC that needs to be known if you are working with