Java Reference
In-Depth Information
Creating a Data Access Class
The previous classes, and in particular the StockTracker class, have responsibility
for the user interface and for controlling the flow of actions between what
the user sees on the screen and the data that goes to or from the database, but
not for accessing the database itself. Keeping that capability separate requires
creating a data access ( DA ) class , which is a class given the responsibility of
accessing the data from its persistent storage and providing it to the requesting
application.
By separating out data access from the way the data is viewed, or presented, a
level of abstraction is inserted, providing greater flexibility for storing the data.
The DA class becomes a model of the database to the GUI program, allowing the
GUI to request data while ignoring the type of database used, or whether a data-
base is used at all. This technique allows the method of storing the data to
change without affecting how the data is accessed by the GUI, only by the DA
class. An additional function that may be abstracted, or separated, into another
class is the control of how the data is used. In this case, the control class decides
whether a user may add or delete other user records, or the number of unsuc-
cessful log on attempts allowed, apart from the code for the actual user interface.
This separation into a model, view, and control is a type of pattern for software
design called model-view-controller ( MVC ). Often, the control and view are
combined into a model-delegate . Although not a strict implementation of all
aspects of the MVC pattern, the StockTrackerDB class represents a model of the
database, while the STLogon, StockTracker, and UserMaintFrame classes handle
their respective view and control responsibilities. Figure 11-36 displays the code
for the StockTrackerDB class.
1 /*
2
Chapter 11: The StockTrackerDB Class
3
Programmer: Michael Mick
4
Date:
December 12, 2007
5
Filename:
StockTrackerDB.java
6
Purpose:
To provide a data access class for the StockTracker database
7 */
8
9 import java.io.*;
10 import java.sql.*;
11 import java.util.*;
12
13 public class StockTrackerDB
14 {
15
private Connection con = null ;
16
17
// Constructor; makes database connection
18
public StockTrackerDB () throws ClassNotFoundException , SQLException
19
{
20
if ( con == null )
21
{
22
String url = "jdbc:odbc:StockTracker" ;
FIGURE 11-36
(continued)
Search WWH ::




Custom Search