Java Reference
In-Depth Information
The results will be as follows:
Driver class found!
Connection created!
Statement created!
111 Mary Worker 1 Main St. Enid OK7777717.5 3
222 Joe Programmer nullnullnullnull17.5 2
Notice the null values for Joe Programmer. In the original insert statement, no address information was supplied,
so the DBMS assigned null values to those fields. We will rectify this by using the update command to change the
information in the existing row for Joe Programmer.
11.
Add the following code before the code added in step 9:
stmt.executeUpdate("UPDATE tntdb.employee " +
"SET street = '2 Maple Ave.', " +
"city = 'Enid', " +
"state = 'OK', " +
"zip = '77777', payrate = 19 " +
"WHERE empnum = '222'");
This update command not only supplies information for the address fields (that previously had null values) but
also changes the pay rate value for employee number 222. Beware: if no WHERE clause had been specified, all the
rows in the table would have been changed and all the rows would have had the same values for the address columns
and payrate. The update command is powerful, but dangerous if used incorrectly!
12.
Run DBAccess as a Java application.
The results will be as follows:
Driver class found!
Connection created!
Statement created!
111 Mary Worker 1 Main St. Enid OK 7777717.5 3
222 Joe Programmer 2 Maple Ave. Enid OK 7777719.0 2
13.
Print out the DBAccess source code.
Class Design for Data Access
Encapsulation is a design goal for Java classes. Encapsulation (also called class abstraction) tries to hide the internal
workings of a class from users of the class (called clients). This means that clients cannot directly access the data
or any “internal” objects used by the class to perform its function. Essentially, this means that internal variables
and methods are defined as private and the encapsulated class provides easy-to-use public methods to manipulate
the private variables and invoke the internal methods. These public methods define the class's client interface .
Encapsulation is good because it simplifies using the class and cuts down on client errors.
There is no better example of the benefits of encapsulation than with a class that accesses a database. Certainly
accessing a database was not easy. Connection objects, driver managers, and statement objects are enough to drive
any programmer nuts! Why not hide all those objects and the required coding inside of private class methods and
have clients execute relatively simple public methods to retrieve and insert to the database?
In the following example, we will also put inheritance to good use and define the various objects needed to
access the database only once in a superclass. All classes that provide DBMS access will be defined as subclasses
thereby inheriting the needed variables, objects, and methods from the superclass. For instance, we already created a
 
Search WWH ::




Custom Search