// Fig. 25.21: GuestDataBean.java // Class GuestDataBean makes a database connection and supports // inserting and retrieving data from the database. package com.deitel.jhtp5.jsp.beans; // Java core packages import java.io.*; import java.sql.*; import java.util.*; public class GuestDataBean { private Connection connection; private Statement statement; // construct TitlesBean object public GuestDataBean() throws Exception { System.setProperty( "db2j.system.home", "C:/Cloudscape_5.0" ); // load the Cloudscape driver Class.forName("com.ibm.db2j.jdbc.DB2jDriver"); // connect to the database connection = DriverManager.getConnection( "jdbc:db2j:guestbook" ); statement = connection.createStatement(); } // return an ArrayList of GuestBeans public List getGuestList() throws SQLException { List guestList = new ArrayList(); // obtain list of titles ResultSet results = statement.executeQuery( "SELECT firstName, lastName, email FROM guests" ); // get row data while ( results.next() ) { GuestBean guest = new GuestBean(); guest.setFirstName( results.getString( 1 ) ); guest.setLastName( results.getString( 2 ) ); guest.setEmail( results.getString( 3 ) ); guestList.add( guest ); } return guestList; } // insert a guest in guestbook database public void addGuest( GuestBean guest ) throws SQLException { statement.executeUpdate( "INSERT INTO guests ( firstName, " + "lastName, email ) VALUES ( '" + guest.getFirstName() + "', '" + guest.getLastName() + "', '" + guest.getEmail() + "' )" ); } // close statements and terminate database connection protected void finalize() { // attempt to close database connection try { statement.close(); connection.close(); } // process SQLException on close operation catch ( SQLException sqlException ) { sqlException.printStackTrace(); } } } /************************************************************************** * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and * * Prentice Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/