Computer Science Example
Using a Data and List class

/* This is a Java application that gets data from a database and stores it
 in an array of objects.  It then displays the contents on the screen. */

import java.sql.*;

public class Library
{
     public static void main (String [] args)
     {
          try
          {
               Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
               Connection con = DriverManager.getConnection ("jdbc:odbc:library");
 
               Statement stmt = con.createStatement ();
               String query = "Select * From Books";
               ResultSet rs = stmt.executeQuery (query);
 
               List list = new List ();
               list.getListData (rs);
               list.displayListData ();
               con.close ();
          } catch (ClassNotFoundException e){System.out.println ("Database connection exception.");}
            catch (SQLException e) {System.out.println ("SQL Exception");}
     } // main
} // class Library

// The Data class is used to store ISBN, Author, Title, BorrowersID, and DueDate.
class Data
{
     private String ISBN, Author, Title, BorrowersID, DueDate;
 
     // getData gets data from the database and stores it in the Data object.
     protected void getData (ResultSet rs) throws SQLException
     {
          ISBN = rs.getString ("ISBN");
          Author = rs.getString ("Author");
          Title = rs.getString ("Title");
          BorrowersID = rs.getString ("BorrowersID");
          DueDate = rs.getString ("DueDate");
     } // readData
 
     // displayData displays the data on the screen.
     protected void displayData ()
     {
          System.out.println ();
          System.out.println ("ISBN: " + ISBN);
          System.out.println ("Author: " + Author);
          System.out.println ("Title: " + Title);
          System.out.println ("BorrowersID: " + BorrowersID);
          System.out.println ("DueDate: " + DueDate);
     } // displayData
} // class Data

/* The List class instantiates an array, gets data from the database and puts it
 into the array.  It then displays the contents of the array on the screen.*/
class List
{
     final int maxSize = 10;
     private Data [] list = new Data [maxSize];
     private int listSize = 0;
 
     // getListData reads the data from the database into the array.
     public void getListData (ResultSet rs) throws SQLException
     {
          int count = 0;
          while ((rs.next ())&& (count < maxSize))
          {
               Data data = new Data ();
               data.getData (rs);
               list [count] = data;
               count ++;
          }
          listSize = count;
     } // getDataFromDatabase
 
     // displayData displays a copy of the list on the screen.
     public void displayListData ()
     {
          System.out.println ("Book List");
          for (int count = 0; count < listSize; count++)
           list [count].displayData ();
     } // displayList
} // class List