Java Advance DB 3

profilewilden
ch28solutions.zip

ch28solutions/ex28_02/DisplayQueryResults$1.class

                synchronized 
                class DisplayQueryResults$1 
                implements java.awt.event.ActionListener {
    void DisplayQueryResults$1(DisplayQueryResults);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_02/DisplayQueryResults$2.class

                synchronized 
                class DisplayQueryResults$2 
                implements java.awt.event.ActionListener {
    void DisplayQueryResults$2(DisplayQueryResults);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_02/DisplayQueryResults$3.class

                synchronized 
                class DisplayQueryResults$3 
                extends java.awt.event.WindowAdapter {
    void DisplayQueryResults$3(DisplayQueryResults);
    
                public void 
                windowClosed(java.awt.event.WindowEvent);
}

            

ch28solutions/ex28_02/DisplayQueryResults.class

                public 
                synchronized 
                class DisplayQueryResults 
                extends javax.swing.JFrame {
    
                static 
                final String 
                DATABASE_URL = jdbc:mysql://localhost/books;
    
                static 
                final String 
                USERNAME = deitel;
    
                static 
                final String 
                PASSWORD = deitel;
    
                static 
                final String 
                DEFAULT_QUERY = SELECT * FROM authors;
    
                private ResultSetTableModel 
                tableModel;
    
                private javax.swing.JTable 
                table;
    
                private javax.swing.JComboBox 
                inputQuery;
    
                private javax.swing.JButton 
                submitQuery;
    
                private javax.swing.JTextField 
                input;
    
                public void DisplayQueryResults();
    
                private void 
                getTable();
    
                public 
                static void 
                main(String[]);
}

            

ch28solutions/ex28_02/DisplayQueryResults.java

ch28solutions/ex28_02/DisplayQueryResults.java

// Fig. 28.28: DisplayQueryResults.java
// Display the contents of the Authors table in the books database.
import  java . awt . * ;
import  java . awt . event . ActionListener ;
import  java . awt . event . ActionEvent ;
import  java . awt . event . WindowAdapter ;
import  java . awt . event . WindowEvent ;
import  java . sql . SQLException ;
import  java . util . regex . PatternSyntaxException ;
import  javax . swing . * ;
import  javax . swing . table . TableRowSorter ;
import  javax . swing . table . TableModel ;

public   class   DisplayQueryResults   extends   JFrame  
{
    // database URL, username and password
    static   final   String  DATABASE_URL  =   "jdbc:mysql://localhost/books" ;
    static   final   String  USERNAME  =   "deitel" ;
    static   final   String  PASSWORD  =   "deitel" ;
   
    // default query retrieves all data from authors table
    static   final   String  DEFAULT_QUERY  =   "SELECT * FROM authors" ;
   
    private   ResultSetTableModel  tableModel ;
    private   JTable  table ;
    private   JComboBox  inputQuery ;
    private   JButton  submitQuery ;
    private   JTextField  input ;
   
    // create ResultSetTableModel and GUI
    public   DisplayQueryResults ()  
    {    
       super (   "Displaying Query Results"   );
        
       // create ResultSetTableModel and display database table
       try  
       {
          // create TableModel for results of query SELECT * FROM authors
         tableModel  =   new   ResultSetTableModel (  DATABASE_URL ,
            USERNAME ,  PASSWORD ,  DEFAULT_QUERY  );
       }   // end try
       catch   (   SQLException  sqlex  )  
       {
          System . err . println (   "Unable to connect"   );
         sqlex . printStackTrace ();
          System . exit (   1   );    // terminate program
       }   // end catch

       String  names []   =   {   "All authors" ,   "All titles" ,  
          "A specific author" ,   "A specific title"   };

       // if connected to database, set up GUI      
      inputQuery  =   new   JComboBox (  names  );

      submitQuery  =   new   JButton (   "Submit query"   );
      submitQuery . addActionListener (
          new   ActionListener ()  
          {
             public   void  actionPerformed (   ActionEvent  e  )  
             {
               getTable ();
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end addActionListener

       JPanel  topPanel  =   new   JPanel ();
      input  =   new   JTextField (   20   );   // for user input query
      input . addActionListener (
          new   ActionListener ()  
          {
             public   void  actionPerformed (   ActionEvent  e  )
             {
                try  
                {
                   String  query  =  input . getText ();
                  tableModel . setQuery (  query  );
                }   // end try
                catch   (   SQLException  sqlex  )  
                {
                  sqlex . printStackTrace ();
                }   // end catch
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end addActionListener
   
       JPanel  centerPanel  =   new   JPanel ();
      centerPanel . setLayout (   new   FlowLayout ()   );
      centerPanel . add (   new   JLabel (   "Enter query, author or title:"   )   );
      centerPanel . add (  input  );
      topPanel . setLayout (   new   BorderLayout ()   );
      topPanel . add (  inputQuery ,   BorderLayout . NORTH  );
      topPanel . add (  centerPanel ,   BorderLayout . CENTER  );
      topPanel . add (  submitQuery ,   BorderLayout . SOUTH  );
 
      table  =   new   JTable (  tableModel  );

       // set up GUI
      setLayout (   new   BorderLayout ()   );
      add (  topPanel ,   BorderLayout . NORTH  );
      add (   new   JScrollPane (  table  ),   BorderLayout . CENTER  );       
      getTable ();
      setSize (   500 ,   500   );
      setVisible (   true   );

       // dispose of window when user quits application (this overrides
       // the default of HIDE_ON_CLOSE)
      setDefaultCloseOperation (  DISPOSE_ON_CLOSE  );
      
       // ensure database connection is closed when user quits application
      addWindowListener (
          new   WindowAdapter ()  
          {
             // disconnect from database and exit when window has closed
             public   void  windowClosed (   WindowEvent  event  )
             {
               tableModel . disconnectFromDatabase ();
                System . exit (   0   );
             }   // end method windowClosed
          }   // end WindowAdapter inner class
       );   // end call to addWindowListener
    }   // end DisplayQueryResults constructor

    // execute query and display result in table
    private   void  getTable ()
    {         
       try  
       {
          int  selection  =  inputQuery . getSelectedIndex ();
          String  query  =   null ;

          // execute predefined query
          switch   (  selection  )  
          {
             case   0 :
               query  =   "SELECT * FROM authors" ;
                break ;
             case   1 :
               query  =   "SELECT * FROM titles" ;
                break ;
             case   2 :
               query  =   "SELECT authors.lastName, authors.firstName, " +
                   "titles.title, titles.isbn FROM "   +
                   "titles INNER JOIN (authorISBN INNER JOIN authors ON"   +
                   " authorISBN.authorID = authors.authorID) ON "   +
                   "titles.isbn = authorISBN.isbn WHERE authors.lastName"   +
                   " = '"   +  input . getText ()   +   "' ORDER BY "   +
                   "authors.lastName, authors.firstName ASC" ;
                   break ;
             case   3 :
               query  =   "SELECT titles.isbn, titles.title, "   +
                   "authors.lastName, authors.firstName FROM titles "   +
                   "INNER JOIN (authorISBN INNER JOIN authors ON "   +
                   "authorISBN.authorID = authors.authorID) ON "   +
                   "titles.ISBN = authorISBN.ISBN WHERE titles.title = '"   +
                  input . getText ()   +   "' ORDER BY authors.lastName, "   +
                   "authors.firstName ASC" ;
                   break ;
          }   // end switch
           
         tableModel . setQuery (  query  );
       }   // end try
       catch   (   SQLException  sqlex  )  
       {
         sqlex . printStackTrace ();

          // recover from invalid query by executing default query
          try  
          {
            tableModel . setQuery (  DEFAULT_QUERY  );
            inputQuery . setSelectedIndex (   0   );
          }   // end try
          catch   (   SQLException  sqlException2  )  
          {
            sqlException2 . printStackTrace ();
            tableModel . disconnectFromDatabase ();   // close connection
             System . exit (   1   );   // terminate application
          }   // end inner catch                   
       }   // end catch
    }   // end method getTable

    // execute application
    public   static   void  main (   String  args []   )  
    {
       new   DisplayQueryResults ();      
    }   // end main
}   // end class DisplayQueryResults



/**************************************************************************
 * (C) Copyright 1992-2012  by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

ch28solutions/ex28_02/java

ch28solutions/ex28_02/ResultSetTableModel.class

                public 
                synchronized 
                class ResultSetTableModel 
                extends javax.swing.table.AbstractTableModel {
    
                private java.sql.Connection 
                connection;
    
                private java.sql.Statement 
                statement;
    
                private java.sql.ResultSet 
                resultSet;
    
                private java.sql.ResultSetMetaData 
                metaData;
    
                private int 
                numberOfRows;
    
                private boolean 
                connectedToDatabase;
    
                public void ResultSetTableModel(String, String, String, String) 
                throws java.sql.SQLException;
    
                public Class 
                getColumnClass(int) 
                throws IllegalStateException;
    
                public int 
                getColumnCount() 
                throws IllegalStateException;
    
                public String 
                getColumnName(int) 
                throws IllegalStateException;
    
                public int 
                getRowCount() 
                throws IllegalStateException;
    
                public Object 
                getValueAt(int, int) 
                throws IllegalStateException;
    
                public void 
                setQuery(String) 
                throws java.sql.SQLException, IllegalStateException;
    
                public void 
                disconnectFromDatabase();
}

            

ch28solutions/ex28_02/ResultSetTableModel.java

ch28solutions/ex28_02/ResultSetTableModel.java

// Fig. 28.25: ResultSetTableModel.java
// A TableModel that supplies ResultSet data to a JTable.
import  java . sql . Connection ;
import  java . sql . Statement ;
import  java . sql . DriverManager ;
import  java . sql . ResultSet ;
import  java . sql . ResultSetMetaData ;
import  java . sql . SQLException ;
import  javax . swing . table . AbstractTableModel ;

// ResultSet rows and columns are counted from 1 and JTable 
// rows and columns are counted from 0. When processing 
// ResultSet rows or columns for use in a JTable, it is 
// necessary to add 1 to the row or column number to manipulate
// the appropriate ResultSet column (i.e., JTable column 0 is 
// ResultSet column 1 and JTable row 0 is ResultSet row 1).
public   class   ResultSetTableModel   extends   AbstractTableModel  
{
    private   Connection  connection ;
    private   Statement  statement ;
    private   ResultSet  resultSet ;
    private   ResultSetMetaData  metaData ;
    private   int  numberOfRows ;

    // keep track of database connection status
    private   boolean  connectedToDatabase  =   false ;
   
    // constructor initializes resultSet and obtains its meta data object;
    // determines number of rows
    public   ResultSetTableModel (   String  url ,   String  username ,
       String  password ,   String  query  )   throws   SQLException
    {          
       // connect to database
      connection  =   DriverManager . getConnection (  url ,  username ,  password  );

       // create Statement to query database
      statement  =  connection . createStatement (  
          ResultSet . TYPE_SCROLL_INSENSITIVE ,
          ResultSet . CONCUR_READ_ONLY  );

       // update database connection status
      connectedToDatabase  =   true ;

       // set query and execute it
      setQuery (  query  );
    }   // end constructor ResultSetTableModel

    // get class that represents column type
    public   Class  getColumnClass (   int  column  )   throws   IllegalStateException
    {
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine Java class of column
       try  
       {
          String  className  =  metaData . getColumnClassName (  column  +   1   );
         
          // return Class object that represents className
          return   Class . forName (  className  );
       }   // end try
       catch   (   Exception  exception  )  
       {
         exception . printStackTrace ();
       }   // end catch
      
       return   Object . class ;   // if problems occur above, assume type Object
    }   // end method getColumnClass

    // get number of columns in ResultSet
    public   int  getColumnCount ()   throws   IllegalStateException
    {    
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine number of columns
       try  
       {
          return  metaData . getColumnCount ();  
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   0 ;   // if problems occur above, return 0 for number of columns
    }   // end method getColumnCount

    // get name of a particular column in ResultSet
    public   String  getColumnName (   int  column  )   throws   IllegalStateException
    {     
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine column name
       try  
       {
          return  metaData . getColumnName (  column  +   1   );   
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   "" ;   // if problems, return empty string for column name
    }   // end method getColumnName

    // return number of rows in ResultSet
    public   int  getRowCount ()   throws   IllegalStateException
    {       
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );
 
       return  numberOfRows ;
    }   // end method getRowCount

    // obtain value in particular row and column
    public   Object  getValueAt (   int  row ,   int  column  )  
       throws   IllegalStateException
    {
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // obtain a value at specified ResultSet row and column
       try  
       {
         resultSet . absolute (  row  +   1   );
          return  resultSet . getObject (  column  +   1   );
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   "" ;   // if problems, return empty string object
    }   // end method getValueAt
   
    // set new database query string
    public   void  setQuery (   String  query  )  
       throws   SQLException ,   IllegalStateException  
    {
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // specify query and execute it
      resultSet  =  statement . executeQuery (  query  );

       // obtain meta data for ResultSet
      metaData  =  resultSet . getMetaData ();

       // determine number of rows in ResultSet
      resultSet . last ();                     // move to last row
      numberOfRows  =  resultSet . getRow ();    // get row number      
      
       // notify JTable that model has changed
      fireTableStructureChanged ();
    }   // end method setQuery

    // close Statement and Connection               
    public   void  disconnectFromDatabase ()             
    {               
       if   (  connectedToDatabase  )                   
       {
          // close Statement and Connection            
          try                                           
          {                                             
            resultSet . close ();                         
            statement . close ();                         
            connection . close ();                        
          }   // end try                                 
          catch   (   SQLException  sqlException  )           
          {                                             
            sqlException . printStackTrace ();            
          }   // end catch                               
          finally    // update database connection status
          {                                             
            connectedToDatabase  =   false ;               
          }   // end finally                             
       }   // end if
    }   // end method disconnectFromDatabase          
}    // end class ResultSetTableModel




/**************************************************************************
 * (C) Copyright 1992-2012  by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

ch28solutions/ex28_03/DatabaseManipulation.class

                public 
                synchronized 
                class DatabaseManipulation {
    
                static 
                final String 
                JDBC_DRIVER = com.mysql.jdbc.Driver;
    
                static 
                final String 
                DATABASE_URL = jdbc:mysql://localhost/books;
    
                static 
                final String 
                USERNAME = deitel;
    
                static 
                final String 
                PASSWORD = deitel;
    
                private java.sql.Connection 
                connection;
    
                private java.sql.Statement 
                statement;
    
                private java.util.Scanner 
                scanner;
    
                public void DatabaseManipulation();
    
                private int 
                getChoice();
    
                private void 
                addAuthor();
    
                private void 
                editAuthor();
    
                private void 
                addTitle();
    
                private void 
                addTitleAuthor();
    
                private void 
                executeSQL(String);
    
                private void 
                displayAuthors();
    
                private void 
                displayISBNs();
    
                private void 
                executeQuery(String);
    
                public 
                static void 
                main(String[]);
}

            

ch28solutions/ex28_03/DatabaseManipulation.java

ch28solutions/ex28_03/DatabaseManipulation.java

// Exercise 28.3 Solution: DatabaseManipulation.java
import  java . sql . Connection ;
import  java . sql . ResultSet ;
import  java . sql . ResultSetMetaData ;
import  java . sql . Statement ;
import  java . sql . DriverManager ;
import  java . sql . SQLException ;
import  java . util . Scanner ;

public   class   DatabaseManipulation  
{
    // JDBC driver and database URL
    static   final   String  JDBC_DRIVER  =   "com.mysql.jdbc.Driver" ;
    static   final   String  DATABASE_URL  =   "jdbc:mysql://localhost/books" ;
    static   final   String  USERNAME  =   "deitel" ;
    static   final   String  PASSWORD  =   "deitel" ;
   
    private   Connection  connection ;   // manages connection
    private   Statement  statement ;   // performs queries
    private   Scanner  scanner ;   // reads user input

    public   DatabaseManipulation ()  
    {    
       // Load the driver to allow connection to the database
       try  
       {
          Class . forName (  JDBC_DRIVER  );   // load database driver class

          // establish connection to database
         connection  =   DriverManager . getConnection (
            DATABASE_URL ,  USERNAME ,  PASSWORD );

          // create Statement for querying database
         statement  =  connection . createStatement ();
       }   // end try
       catch   (   ClassNotFoundException  cnfex  )  
       {
          System . err . println (   "Failed to load JDBC driver."   );
         cnfex . printStackTrace ();
          System . exit (   1   );    // terminate program
       }   // end catch
       catch   (   SQLException  sqlex  )  
       {
          System . err . println (   "Unable to connect"   );
         sqlex . printStackTrace ();
          System . exit (   1   );    // terminate program
       }   // end catch

       // create Scanner for user input
      scanner  =   new   Scanner (   System . in  );

       int  choice  =  getChoice ();

       // process user request
       while   (  choice  !=   5   )
       {
          switch (  choice  )
          {
             case   1 :   // add new author
               addAuthor ();
                break ;
             case   2 :   // edit existing author
               editAuthor ();
                break ;
             case   3 :   // add new title
               addTitle ();
                break ;
             case   4 :   // associate title with author
               addTitleAuthor ();
                break ;
             default :
                System . out . println (   "invalid input"   );
          }   // end switch

         choice  =  getChoice ();
       }   // end while
    }   // end DisplayQueryResult constructor

    // get user choice
    private   int  getChoice ()
    {         
       System . out . println (   "Please choose one action:"   );
       System . out . println (   "1 -- Add a new author"   );
       System . out . println (  
          "2 -- Edit the existing information for an author"   );
       System . out . println (   "3 -- Add a new title for an author"   );
       System . out . println (   "4 -- Associate new title with an author"   );
       System . out . println (   "5 -- Exit"   );
       return  scanner . nextInt ();   // get user choice
    }   // end method getChoice

    // add new author to database
    private   void  addAuthor ()  
    {
       // get first name and last name of the author
       System . out . println (   "Please enter author's first name"   );
       String  firstName  =  scanner . next ();
       System . out . println (   "Please enter author's last name"   );
       String  lastName  =  scanner . next ();

       // insert author into authors table
       String  insertSQL  =   "INSERT INTO authors ( firstName, lastName ) "   +
          "VALUES ( '"   +  firstName  +   "', '"   +  lastName  +   "' )" ;

      executeSQL (  insertSQL  );   // execute SQL
    }   // end method addAuthor

    // edit existing author
    private   void  editAuthor ()
    {
       // get author id, first name and last name
       System . out . println (   "Please enter author id"   );
       int  id  =  scanner . nextInt ();
       System . out . println (   "Please enter new first name"   );
       String  firstName  =  scanner . next ();
       System . out . println (   "Please enter new last name"   );
       String  lastName  =  scanner . next ();

       // update author
       String  updateSQL  =   "UPDATE authors SET firstName = '"   +  firstName  +
          "', lastName = '"   +  lastName  +   "' WHERE authorID = "   +  id ;

      executeSQL (  updateSQL  );   // execute SQL
    }   // end method editAuthor

    // add new title to database
    private   void  addTitle ()
    {
       // get ISBN, title, editionNumber, copyright, publisherID, 
       // imageFile and price
       System . out . println (   "Please enter ISBN"   );
       String  isbn  =  scanner . next ();
       System . out . println (   "Please enter title"   );
      scanner . nextLine ();   // read remaining characters from last input
       String  title  =  scanner . nextLine ();
       System . out . println (   "Please enter edition number"   );
       int  editionNumber  =  scanner . nextInt ();
       System . out . println (   "Please enter copyright year"   );
       String  copyright  =  scanner . next ();

       // insert title into titles table
       String  insertSQL  =   "INSERT INTO titles ( isbn, title, "   +  
          "editionNumber, copyright ) "   +    "VALUES ( '"   +  isbn  +
          "', '"   +  title  +   "', '"   +  editionNumber  +
          "', "   +  copyright  +   " )" ;

      executeSQL (  insertSQL  );   // execute SQL
    }   // end method addTitle

    // associate title with author
    private   void  addTitleAuthor ()
    {
       // get author ID
       System . out . println (  
          "Please choose an author ID from the list below:"   );
      displayAuthors ();
       int  authorID  =  scanner . nextInt ();

       // get title isbn
       System . out . println (
          "Please choose a book isbn from the list below:"   );
      displayISBNs ();
       String  isbn  =  scanner . next ();

       // update authorISBN table
       String  insertSQL  =   "INSERT INTO authorISBN VALUES ( "   +
         authorID  +   ", '"   +  isbn  +   "' )" ;

      executeSQL (  insertSQL  );   // execute SQL
    }   // end method addTitleAuthor

    // execute SQL
    private   void  executeSQL (   String  sqlStatement  )
    {
       // execute specified SQL statement
       try
       {
          System . out . printf (   "Sending SQL: %s\n" ,  sqlStatement  );
          int  result  =  statement . executeUpdate (  sqlStatement  );  

          // display result of SQL execution
          if   (  result  ==   1   )
             System . out . println (   "Update successful\n"   );
          else
             System . out . println (   "Update failed\n"   );
       }   // end try
       catch   (   SQLException  exception  )
       {
         exception . printStackTrace ();
       }   // end catch
    }   // end method executeSQL

    // display authors table
    private   void  displayAuthors ()
    {
       String  query  =  
          "SELECT authorID, firstName, lastName FROM authors" ;
      executeQuery (  query  );
    }   // end method displayAuthors

    // display book title and isbn
    private   void  displayISBNs ()
    {
       String  query  =   "SELECT isbn, editionNumber, title FROM titles" ;
      executeQuery (  query  );
    }   // end method displayISBNs

    // execute query
    private   void  executeQuery (   String  query  )
    {
       // execute query and display result
       try
       {
          // query database
          ResultSet  resultSet  =  statement . executeQuery (  query  );
         
          // process query results
          ResultSetMetaData  metaData  =  resultSet . getMetaData ();
          int  numberOfColumns  =  metaData . getColumnCount ();

          for   (   int  i  =   1 ;  i  <=  numberOfColumns ;  i ++   )
             System . out . printf (   "%-8s\t" ,  metaData . getColumnName (  i  )   );
          System . out . println ();
         
          while   (  resultSet . next ()   )  
          {
             for   (   int  i  =   1 ;  i  <=  numberOfColumns ;  i ++   )
                System . out . printf (   "%-8s\t" ,  resultSet . getObject (  i  )   );
             System . out . println ();
          }   // end while
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
    }   // end method executeQuery

    public   static   void  main (   String  args []   )  
    {
       new   DatabaseManipulation ();
    }   // end main
}   // end class DatabaseManipulation


/**************************************************************************
 * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

 

ch28solutions/ex28_04/AddEmployees$1.class

                synchronized 
                class AddEmployees$1 
                extends java.awt.event.WindowAdapter {
    void AddEmployees$1(AddEmployees);
    
                public void 
                windowClosed(java.awt.event.WindowEvent);
}

            

ch28solutions/ex28_04/AddEmployees$ButtonHandler.class

                synchronized 
                class AddEmployees$ButtonHandler 
                implements java.awt.event.ActionListener {
    
                private void AddEmployees$ButtonHandler(AddEmployees);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_04/AddEmployees.class

                public 
                synchronized 
                class AddEmployees 
                extends javax.swing.JFrame {
    
                static 
                final String 
                JDBC_DRIVER = com.mysql.jdbc.Driver;
    
                static 
                final String 
                DATABASE_URL = jdbc:mysql://localhost/employees;
    
                static 
                final String 
                USERNAME = deitel;
    
                static 
                final String 
                PASSWORD = deitel;
    
                static 
                final String 
                DEFAULT_QUERY = SELECT * FROM employees;
    
                private java.sql.Connection 
                connection;
    
                private java.sql.Statement 
                statement;
    
                private ResultSetTableModel 
                tableModel;
    
                private javax.swing.JTable 
                table;
    
                private javax.swing.JButton 
                addEmployee;
    
                private javax.swing.JButton 
                addSalariedEmployee;
    
                private javax.swing.JButton 
                addCommissionEmployee;
    
                private javax.swing.JButton 
                addBasePlusCommissionEmployee;
    
                private javax.swing.JButton 
                addHourlyEmployee;
    
                public void AddEmployees();
    
                private void 
                addEmployee(String);
    
                public 
                static void 
                main(String[]);
}

            

ch28solutions/ex28_04/AddEmployees.java

ch28solutions/ex28_04/AddEmployees.java

// Exercise 25.4 solution: AddEmployees.java
import  java . sql . Connection ;
import  java . sql . Statement ;
import  java . sql . SQLException ;
import  java . awt . FlowLayout ;
import  java . awt . BorderLayout ;
import  java . awt . event . ActionListener ;
import  java . awt . event . ActionEvent ;
import  java . awt . event . WindowAdapter ;
import  java . awt . event . WindowEvent ;
import  javax . swing . JFrame ;
import  javax . swing . JTable ;
import  javax . swing . JButton ;
import  javax . swing . JPanel ;
import  javax . swing . JLabel ;
import  javax . swing . JScrollPane ;
import  javax . swing . JOptionPane ;

public   class   AddEmployees   extends   JFrame  
{
    // JDBC driver and database URL
    static   final   String  JDBC_DRIVER  =   "com.mysql.jdbc.Driver" ;
    static   final   String  DATABASE_URL  =   "jdbc:mysql://localhost/employees" ;
    static   final   String  USERNAME  =   "deitel" ;
    static   final   String  PASSWORD  =   "deitel" ;

    // default query retrieves all data from employees table
    static   final   String  DEFAULT_QUERY  =   "SELECT * FROM employees" ;
   
    private   Connection  connection ;
    private   Statement  statement ;
    private   ResultSetTableModel  tableModel ;
    private   JTable  table ;
    private   JButton  addEmployee ;
    private   JButton  addSalariedEmployee ;
    private   JButton  addCommissionEmployee ;
    private   JButton  addBasePlusCommissionEmployee ;
    private   JButton  addHourlyEmployee ;

    public   AddEmployees ()
    {
       super (   "Add Employees"   );

       // create ResultSetTableModel with default JDBC driver, 
       // database URL and query
       try  
       {
          // create TableModel for results of query SELECT * FROM employees
         tableModel  =   new   ResultSetTableModel (  JDBC_DRIVER ,  DATABASE_URL ,  
            USERNAME ,  PASSWORD ,  DEFAULT_QUERY  );

         connection  =  tableModel . getConnection ();
       }   // end try
       catch   (   ClassNotFoundException  cnfex  )  
       {
          System . err . println (   "Failed to load JDBC driver."   );
         cnfex . printStackTrace ();
          System . exit (   1   );    // terminate program
       }   // end catch
       catch   (   SQLException  sqlex  )  
       {
          System . err . println (   "Unable to connect"   );
         sqlex . printStackTrace ();
          System . exit (   1   );    // terminate program
       }   // end catch

       // if connected to database, set up GUI      
       JPanel  topPanel  =   new   JPanel ();
      addEmployee  =   new   JButton (   "Add Generic Employee"   );
      addEmployee . addActionListener (   new   ButtonHandler ()   );
      topPanel . add (  addEmployee  );

       // create four buttons that allow user to add specific employee
      addSalariedEmployee  =   new   JButton (   "Add Salaried Employee"   );
      addSalariedEmployee . addActionListener (   new   ButtonHandler ()   );

      addCommissionEmployee  =   new   JButton (   "Add Commission Employee"   );
      addCommissionEmployee . addActionListener (   new   ButtonHandler ()   );

      addBasePlusCommissionEmployee  =
          new   JButton (   "Add Base Plus Commission Employee"   );
      addBasePlusCommissionEmployee . addActionListener (  
          new   ButtonHandler ()   );

      addHourlyEmployee  =   new   JButton (   "Add Hourly Employee"   );
      addHourlyEmployee . addActionListener (   new   ButtonHandler ()   );

       // add four buttons to centerPanel
       JPanel  centerPanel  =   new   JPanel ();
      centerPanel . add (  addSalariedEmployee  );
      centerPanel . add (  addCommissionEmployee  );
      centerPanel . add (  addBasePlusCommissionEmployee  );
      centerPanel . add (  addHourlyEmployee  );

       JPanel  inputPanel  =   new   JPanel ();
      inputPanel . setLayout (   new   BorderLayout ()   );
      inputPanel . add (  topPanel ,   BorderLayout . NORTH  );
      inputPanel . add (  centerPanel ,   BorderLayout . CENTER  );

      table  =   new   JTable (  tableModel  );

      setLayout (   new   BorderLayout ()   );
      add (  inputPanel ,   BorderLayout . NORTH  );
      add (   new   JScrollPane (  table  ),   BorderLayout . CENTER  );

      setSize (   800 ,   300   );
      setVisible (   true   );

       // dispose of window when user quits application (this overrides
       // the default of HIDE_ON_CLOSE)
      setDefaultCloseOperation (  DISPOSE_ON_CLOSE  );
      
       // ensure database connection is closed when user quits application
      addWindowListener (
          new   WindowAdapter ()  
          {
             // disconnect from database and exit when window has closed
             public   void  windowClosed (   WindowEvent  event  )
             {
               tableModel . disconnectFromDatabase ();
                System . exit (   0   );
             }   // end method windowClosed
          }   // end WindowAdapter inner class
       );   // end call to addWindowListener
    }   // end AddEmployees constructor

    // add employee to database
    private   void  addEmployee (   String  query  )
    {         
       try  
       {
         statement  =  connection . createStatement ();
         statement . executeUpdate (  query  );  
         tableModel . setQuery (  DEFAULT_QUERY  );
       }   // end try
       catch   (   SQLException  sqlex  )  
       {
         sqlex . printStackTrace ();
       }   // end catch
    }   // end addEmployee

    public   static   void  main (   String []  args  )  
    {
       new   AddEmployees ();
    }   // end main
 
    // inner class ButtonHandler handles button event
    private   class   ButtonHandler   implements   ActionListener  
    {
       public   void  actionPerformed (   ActionEvent  event  )
       {
          String  socialSecurityNumber  =   JOptionPane . showInputDialog (
             "Employee Social Security Number"   );
          String  insertQuery  =   "" ,  displayQuery  =   "" ;

          // add generic employee to table employees
          if   (  event . getSource ()   ==  addEmployee  )
          {
             String  firstName  =
                JOptionPane . showInputDialog (   "First Name"   );
             String  lastName  =   JOptionPane . showInputDialog (   "Last Name"   );
             String  birthday  =  
                JOptionPane . showInputDialog (   "Birthday"   );
             String  employeeType  =  
                JOptionPane . showInputDialog (   "Employee Type"   );
             String  department  =  
                JOptionPane . showInputDialog (   "Department Name"   );
            insertQuery  =   "INSERT INTO employees VALUES ( '"   +
               socialSecurityNumber  +   "', '"   +  firstName  +   "', '"   +
               lastName  +   "', '"   +  birthday  +   "', '"   +  employeeType  +
                "', '"   +  department  +   "' )" ;
            displayQuery  =   "SELECT socialSecurityNumber, firstName, "   +
                "lastName, birthday, employeeType, departmentName FROM "   +
                "employees" ;
          }   // end if

          // add salaried employee to table salariedEmployees
          else   if   (  event . getSource ()   ==  addSalariedEmployee  )  
          {
             double  weeklySalary  =   Double . parseDouble (  
                JOptionPane . showInputDialog (   "Weekly Salary:"   )   );
            insertQuery  =   "INSERT INTO salariedEmployees VALUES ( '"   +
               socialSecurityNumber  +   "', '"   +  weeklySalary  +   "', '0' )" ;
            displayQuery  =   "SELECT employees.socialSecurityNumber, "   +  
                "employees.firstName, employees.lastName, "   +  
                "employees.employeeType, salariedEmployees.weeklySalary"   +
                " FROM employees, salariedEmployees WHERE "   +  
                "employees.socialSecurityNumber = "   +  
                "salariedEmployees.socialSecurityNumber" ;
          }   // end if

          // add commission employee to table commissionEmployees
          else   if   (  event . getSource ()   ==  addCommissionEmployee  )  
          {
             int  grossSales  =   Integer . parseInt (
                JOptionPane . showInputDialog (   "Gross Sales:"   )   );
             double  commissionRate  =   Double . parseDouble (
                JOptionPane . showInputDialog (   "Commission Rate:"   )   );
            insertQuery  =   "INSERT INTO commissionEmployees VALUES ( '"   +
               socialSecurityNumber  +   "', '"   +  grossSales  +   "', '"   +
               commissionRate  +   "', '0' )" ;
            displayQuery  =   "SELECT employees.socialSecurityNumber, "   +  
                "employees.firstName, employees.lastName, "   +  
                "employees.employeeType, commissionEmployees.grossSales,"   +
                " commissionEmployees.commissionRate FROM employees, "   +  
                "commissionEmployees WHERE employees.socialSecurityNumber="  
                +   "commissionEmployees.socialSecurityNumber" ;
          }   // end else if

          // add base plus commission employee to table 
          // basePlusCommissionEmployees
          else   if   (  event . getSource ()   ==  addBasePlusCommissionEmployee  )  
          {
             int  grossSales  =   Integer . parseInt (
                JOptionPane . showInputDialog (   "Gross Sales:"   )   );
             double  commissionRate  =   Double . parseDouble (
                JOptionPane . showInputDialog (   "Commission Rate:"   )   );
             double  baseSalary  =   Double . parseDouble (
                JOptionPane . showInputDialog (   "Base Salary:"   )   );
            insertQuery  =   "INSERT INTO basePlusCommissionEmployees "   +  
                "VALUES ( '"   +  socialSecurityNumber  +   "', '"   +  grossSales  +  
                "', '"   +  commissionRate  +   "', '"   +  baseSalary  +   "', '0' )" ;
            displayQuery  =   "SELECT employees.socialSecurityNumber, "   +  
                "employees.firstName, employees.lastName, employees."   +  
                "employeeType, basePlusCommissionEmployees.baseSalary, "   +
                "basePlusCommissionEmployees.grossSales, basePlus"   +  
                "CommissionEmployees.commissionRate FROM employees, "   +
                "basePlusCommissionEmployees WHERE "   +  
                "employees.socialSecurityNumber = "   +  
                "basePlusCommissionEmployees.socialSecurityNumber" ;
          }   // end else if

          // add hourly employee to table hourlyEmployees
          else  
          {
             int  hours  =   Integer . parseInt (
                JOptionPane . showInputDialog (   "Hours:"   )   );
             double  wage  =   Double . parseDouble (
                JOptionPane . showInputDialog (   "Wage:"   )   );
            insertQuery  =   "INSERT INTO hourlyEmployees VALUES ( '"   +
               socialSecurityNumber  +   "', '"   +  hours  +   "', '"   +  wage  +  
                "', '0' )" ;
            displayQuery  =   "SELECT employees.socialSecurityNumber, "   +  
                "employees.firstName, employees.lastName, "   +  
                "employees.employeeType, hourlyEmployees.hours, "   +
                "hourlyEmployees.wage FROM employees, hourlyEmployees "   +
                "WHERE employees.socialSecurityNumber = "   +  
                "hourlyEmployees.socialSecurityNumber" ;
          }   // end else

          // execute insert query and display employee info
          try  
          {
            statement  =  connection . createStatement ();
            statement . executeUpdate (  insertQuery  );    

             // display the employee info
            tableModel . setQuery (  displayQuery  );
          }   // end try
          catch   (   SQLException  exception  )  
          {
             JOptionPane . showMessageDialog (   null ,  exception . toString ()   );
          }   // end catch
       }   // end method actionPerformed
    }   // end inner class ButtonHandler
}   // end class AddEmployees


/**************************************************************************
 * (C) Copyright 1992-2012  by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

ch28solutions/ex28_04/employees.sql

CREATE DATABASE IF NOT EXISTS employees; USE employees; DROP TABLE IF EXISTS salariedEmployees; DROP TABLE IF EXISTS commissionEmployees; DROP TABLE IF EXISTS basePlusCommissionEmployees; DROP TABLE IF EXISTS hourlyEmployees; DROP TABLE IF EXISTS employees; CREATE TABLE employees ( socialSecurityNumber varchar (30) NOT NULL, firstName varchar (30) NOT NULL, lastName varchar (30) NOT NULL, birthday date NOT NULL, employeeType varchar (30) NOT NULL, departmentName varchar (30) NOT NULL, PRIMARY KEY (socialSecurityNumber) ) TYPE=INNODB; CREATE TABLE salariedEmployees ( socialsecurityNumber varchar (30) NOT NULL, weeklySalary real NOT NULL, bonus real, INDEX (socialSecurityNumber), FOREIGN KEY (socialSecurityNumber) REFERENCES employees (socialSecurityNumber) ) TYPE=INNODB; CREATE TABLE commissionEmployees ( socialSecurityNumber varchar (30) NOT NULL, grossSales int NOT NULL, commissionRate real NOT NULL, bonus real, INDEX (socialSecurityNumber), FOREIGN KEY (socialSecurityNumber) REFERENCES employees (socialSecurityNumber) ) TYPE=INNODB; CREATE TABLE basePlusCommissionEmployees ( socialSecurityNumber varchar (30) NOT NULL, grossSales int NOT NULL, commissionRate real NOT NULL, baseSalary real NOT NULL, bonus real, INDEX (socialSecurityNumber), FOREIGN KEY (socialSecurityNumber) REFERENCES employees (socialSecurityNumber) ) TYPE=INNODB; CREATE TABLE hourlyEmployees ( socialSecurityNumber varchar (30) NOT NULL, hours int NOT NULL, wage real NOT NULL, bonus real, INDEX (socialSecurityNumber), FOREIGN KEY (socialSecurityNumber) REFERENCES employees (socialSecurityNumber) ) TYPE=INNODB; INSERT INTO employees VALUES ('111-11-1111', 'John', 'Smith', '1945-1-2', 'salariedEmployee', 'R&D'); INSERT INTO employees VALUES ('222-22-2222', 'Sue', 'Jones', '1961-2-3', 'commissionEmployee', 'SALES'); INSERT INTO employees VALUES ('333-33-3333', 'Bob', 'Lowis', '1958-10-5', 'basePlusCommissionEmployee', 'SALES'); INSERT INTO employees VALUES ('444-44-4444', 'Karen', 'Price', '1972-5-25', 'hourlyEmployee', 'HR'); INSERT INTO salariedEmployees VALUES ('111-11-1111', 2013.67, 0); INSERT INTO commissionEmployees VALUES ('222-22-2222', 10100, 0.05, 0); INSERT INTO basePlusCommissionEmployees VALUES ('333-33-3333', 5000, 0.04, 300, 0); INSERT INTO hourlyEmployees VALUES ('444-44-4444', 30, 35.5, 0);

ch28solutions/ex28_04/ResultSetTableModel.class

                public 
                synchronized 
                class ResultSetTableModel 
                extends javax.swing.table.AbstractTableModel {
    
                private java.sql.Connection 
                connection;
    
                private java.sql.Statement 
                statement;
    
                private java.sql.ResultSet 
                resultSet;
    
                private java.sql.ResultSetMetaData 
                metaData;
    
                private int 
                numberOfRows;
    
                private boolean 
                connectedToDatabase;
    
                public void ResultSetTableModel(String, String, String, String, String) 
                throws java.sql.SQLException, ClassNotFoundException;
    
                public Class 
                getColumnClass(int) 
                throws IllegalStateException;
    
                public int 
                getColumnCount() 
                throws IllegalStateException;
    
                public String 
                getColumnName(int) 
                throws IllegalStateException;
    
                public int 
                getRowCount() 
                throws IllegalStateException;
    
                public Object 
                getValueAt(int, int) 
                throws IllegalStateException;
    
                public void 
                setQuery(String) 
                throws java.sql.SQLException, IllegalStateException;
    
                public void 
                disconnectFromDatabase();
    
                public java.sql.Connection 
                getConnection();
}

            

ch28solutions/ex28_04/ResultSetTableModel.java

ch28solutions/ex28_04/ResultSetTableModel.java

// Exercise 25.4 Solution: ResultSetTableModel.java
// A TableModel that supplies ResultSet data to a JTable.
import  java . sql . Connection ;
import  java . sql . Statement ;
import  java . sql . DriverManager ;
import  java . sql . ResultSet ;
import  java . sql . ResultSetMetaData ;
import  java . sql . SQLException ;
import  javax . swing . table . AbstractTableModel ;

// ResultSet rows and columns are counted from 1 and JTable 
// rows and columns are counted from 0. When processing 
// ResultSet rows or columns for use in a JTable, it is 
// necessary to add 1 to the row or column number to manipulate
// the appropriate ResultSet column (i.e., JTable column 0 is 
// ResultSet column 1 and JTable row 0 is ResultSet row 1).
public   class   ResultSetTableModel   extends   AbstractTableModel  
{
    private   Connection  connection ;
    private   Statement  statement ;
    private   ResultSet  resultSet ;
    private   ResultSetMetaData  metaData ;
    private   int  numberOfRows ;

    // keep track of database connection status 
    private   boolean  connectedToDatabase  =   false ;
   
    // constructor initializes resultSet and obtains its meta data object;
    // determines number of rows
    public   ResultSetTableModel (   String  driver ,   String  url ,  
       String  username ,   String  password ,   String  query  )  
       throws   SQLException ,   ClassNotFoundException
    {
       Class . forName (  driver  );   // load database driver class
      connection  =   DriverManager . getConnection (  url ,  username ,  password  );

       // create Statement to query database   
      statement  =  connection . createStatement (  
          ResultSet . TYPE_SCROLL_INSENSITIVE ,    
          ResultSet . CONCUR_READ_ONLY  );         

      connectedToDatabase  =   true ;   // update database connection status
      setQuery (  query  );   // set query and execute it
    }   // end constructor ResultSetTableModel

    // get class that represents column type
    public   Class  getColumnClass (   int  column  )   throws   IllegalStateException
    {
       // ensure database connection is available                        
       if   (   ! connectedToDatabase  )                                        
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine Java class of column
       try  
       {
          String  className  =  metaData . getColumnClassName (  column  +   1   );
         
          // return Class object that represents className
          return   Class . forName (  className  );               
       }   // end try
       catch   (   Exception  exception  )  
       {
         exception . printStackTrace ();
       }   // end catch
      
       return   Object . class ;   // if problems occur above, assume type Object
    }   // end method getColumnClass

    // get number of columns in ResultSet
    public   int  getColumnCount ()   throws   IllegalStateException
    {    
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine number of columns
       try  
       {
          return  metaData . getColumnCount ();  
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   0 ;   // if problems occur above, return 0 for number of columns
    }   // end method getColumnCount

    // get name of a particular column in ResultSet
    public   String  getColumnName (   int  column  )   throws   IllegalStateException
    {     
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine column name
       try  
       {
          return  metaData . getColumnName (  column  +   1   );   
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   "" ;   // if problems, return empty string for column name
    }   // end method getColumnName

    // return number of rows in ResultSet
    public   int  getRowCount ()   throws   IllegalStateException
    {       
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );
 
       return  numberOfRows ;
    }   // end method getRowCount

    // obtain value in particular row and column
    public   Object  getValueAt (   int  row ,   int  column  )  
       throws   IllegalStateException
    {
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // obtain a value at specified ResultSet row and column
       try  
       {
         resultSet . absolute (  row  +   1   );
          return  resultSet . getObject (  column  +   1   );
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   "" ;   // if problems, return empty string object
    }   // end method getValueAt
   
    // set new database query string
    public   void  setQuery (   String  query  )  
       throws   SQLException ,   IllegalStateException  
    {
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

      resultSet  =  statement . executeQuery (  query  );   // execute query
      metaData  =  resultSet . getMetaData ();   // get metadata

       // determine number of rows in ResultSet
      resultSet . last ();   // move to last row
      numberOfRows  =  resultSet . getRow ();   // get row number      
      fireTableStructureChanged ();   // table model changed
    }   // end method setQuery

    // close Statement and Connection               
    public   void  disconnectFromDatabase ()             
    {                                                
       // close Statement and Connection            
       try                                           
       {                                             
         statement . close ();                         
         connection . close ();                        
       }   // end try                                 
       catch   (   SQLException  sqlException  )           
       {                                             
         sqlException . printStackTrace ();            
       }   // end catch                               
       finally    // update database connection status
       {                                             
         connectedToDatabase  =   false ;               
       }   // end finally                             
    }   // end method disconnectFromDatabase          

    // return Connection
    public   Connection  getConnection ()
    {
       return  connection ;
    }   // end method getConnection
}    // end class ResultSetTableModel





/**************************************************************************
 * (C) Copyright 1992-2012  by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

ch28solutions/ex28_05/DisplayQueryResults$1.class

                synchronized 
                class DisplayQueryResults$1 
                implements java.awt.event.ActionListener {
    void DisplayQueryResults$1(DisplayQueryResults);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_05/DisplayQueryResults$2.class

                synchronized 
                class DisplayQueryResults$2 
                implements java.awt.event.ActionListener {
    void DisplayQueryResults$2(DisplayQueryResults);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_05/DisplayQueryResults$3.class

                synchronized 
                class DisplayQueryResults$3 
                extends java.awt.event.WindowAdapter {
    void DisplayQueryResults$3(DisplayQueryResults);
    
                public void 
                windowClosed(java.awt.event.WindowEvent);
}

            

ch28solutions/ex28_05/DisplayQueryResults.class

                public 
                synchronized 
                class DisplayQueryResults 
                extends javax.swing.JFrame {
    
                static 
                final String 
                JDBC_DRIVER = com.mysql.jdbc.Driver;
    
                static 
                final String 
                DATABASE_URL = jdbc:mysql://localhost/employees;
    
                static 
                final String 
                USERNAME = deitel;
    
                static 
                final String 
                PASSWORD = deitel;
    
                static 
                final String 
                DEFAULT_QUERY = SELECT * FROM employees;
    
                private java.sql.Connection 
                connection;
    
                private java.sql.Statement 
                statement;
    
                private ResultSetTableModel 
                tableModel;
    
                private javax.swing.JTable 
                table;
    
                private javax.swing.JComboBox 
                inputQuery;
    
                private javax.swing.JButton 
                submitQuery;
    
                private javax.swing.JTextField 
                input;
    
                public void DisplayQueryResults();
    
                private void 
                getTable();
    
                public 
                static void 
                main(String[]);
}

            

ch28solutions/ex28_05/DisplayQueryResults.java

ch28solutions/ex28_05/DisplayQueryResults.java

// Exercise 25.5 Solution: DisplayQueryResults.java
import  java . sql . SQLException ;
import  java . sql . Connection ;
import  java . sql . Statement ;
import  java . awt . FlowLayout ;
import  java . awt . BorderLayout ;
import  java . awt . event . ActionListener ;
import  java . awt . event . ActionEvent ;
import  java . awt . event . WindowAdapter ;
import  java . awt . event . WindowEvent ;
import  javax . swing . JFrame ;
import  javax . swing . JTable ;
import  javax . swing . JComboBox ;
import  javax . swing . JButton ;
import  javax . swing . JTextField ;
import  javax . swing . JScrollPane ;
import  javax . swing . JPanel ;
import  javax . swing . JLabel ;

public   class   DisplayQueryResults   extends   JFrame  
{
    // JDBC driver and database URL
    static   final   String  JDBC_DRIVER  =   "com.mysql.jdbc.Driver" ;
    static   final   String  DATABASE_URL  =   "jdbc:mysql://localhost/employees" ;
    static   final   String  USERNAME  =   "deitel" ;
    static   final   String  PASSWORD  =   "deitel" ;

    // default query retrieves all data from employees table
    static   final   String  DEFAULT_QUERY  =   "SELECT * FROM employees" ;

    private   Connection  connection ;
    private   Statement  statement ;
    private   ResultSetTableModel  tableModel ;
    private   JTable  table ;
    private   JComboBox  inputQuery ;
    private   JButton  submitQuery ;
    private   JTextField  input ;
    
    public   DisplayQueryResults ()  
    {    
       super (   "Select Query. Click Submit to See Results."   );

       // create ResultSetTableModel with default JDBC driver, 
       // database URL and query
       try  
       {
          // create TableModel for results of query SELECT * FROM employees
         tableModel  =   new   ResultSetTableModel (  JDBC_DRIVER ,  DATABASE_URL ,  
            USERNAME ,  PASSWORD ,  DEFAULT_QUERY  );

         connection  =  tableModel . getConnection ();
       }   // end try
       catch   (   ClassNotFoundException  cnfex  )  
       {
          System . err . println (   "Failed to load JDBC driver."   );
         cnfex . printStackTrace ();
          System . exit (   1   );    // terminate program
       }   // end catch
       catch   (   SQLException  sqlex  )  
       {
          System . err . println (   "Unable to connect"   );
         sqlex . printStackTrace ();
          System . exit (   1   );    // terminate program
       }   // end catch

       String  queries []   =   {   "Select all employees working in Department "   +  
          "SALES." ,   "Select hourly employees working over 30 hours." ,  
          "Select all comission employees in descending order of the "   +
          "comission rate." ,   "Specify particular query"   };

       // set up GUI      
      inputQuery  =   new   JComboBox (  queries  );
      submitQuery  =   new   JButton (   "Submit query"   );
      submitQuery . addActionListener (
          new   ActionListener ()  
          {
             public   void  actionPerformed (   ActionEvent  e  )  
             {
               getTable ();
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

       JPanel  topPanel  =   new   JPanel ();
      input  =   new   JTextField (   40   );
      input . addActionListener (
          new   ActionListener ()  
          {
             public   void  actionPerformed (   ActionEvent  e  )
             {
                // execute query in JTextField
                try  
                {
                   String  query  =  input . getText ();

                   if   (  query . substring (   0 ,   6   ). equalsIgnoreCase (  
                      "SELECT"   )   )
                     tableModel . setQuery (  query  );
                   else  
                     statement . executeUpdate (  query  );          
                }   // end try
                catch   (   SQLException  sqlex  )  
                {
                  sqlex . printStackTrace ();
                }   // end catch
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

       JPanel  centerPanel  =   new   JPanel ();
      centerPanel . setLayout (   new   FlowLayout ()   );
      centerPanel . add (   new   JLabel (   "Enter query:"   )   );
      centerPanel . add (  input  );
      topPanel . setLayout (   new   BorderLayout ()   );
      topPanel . add (  inputQuery ,   BorderLayout . NORTH  );
      topPanel . add (  centerPanel ,   BorderLayout . CENTER  );
      topPanel . add (  submitQuery ,   BorderLayout . SOUTH  );
 
      table  =   new   JTable (  tableModel  );
      setLayout (   new   BorderLayout ()   );
      add (  topPanel ,   BorderLayout . NORTH  );
      add (   new   JScrollPane (  table  ),   BorderLayout . CENTER  );       

      getTable ();

      setSize (   650 ,   200   );
      setVisible (   true   );

       // dispose of window when user quits application (this overrides
       // the default of HIDE_ON_CLOSE)
      setDefaultCloseOperation (  DISPOSE_ON_CLOSE  );
      
       // ensure database connection is closed when user quits application
      addWindowListener (
          new   WindowAdapter ()  
          {
             // disconnect from database and exit when window has closed
             public   void  windowClosed (   WindowEvent  event  )
             {
               tableModel . disconnectFromDatabase ();
                System . exit (   0   );
             }   // end method windowClosed
          }   // end WindowAdapter inner class
       );   // end call to addWindowListener
    }   // end constructor DisplayQueryResult

    // execute query selected from JComboBox
    private   void  getTable ()
    {        
       // define each query
       try  
       {
          int  selection  =  inputQuery . getSelectedIndex ();
          String  query  =   null ;

          switch   (  selection  )  
          {
             case   0 :   // select employees from the SALES department
               query  =   "SELECT * FROM employees WHERE "   +  
                   "departmentName = 'SALES'" ;
                break ;
             case   1 :   // select hourly employees working over 30 hours
               query  =   "SELECT * FROM hourlyEmployees WHERE hours >= 30" ;
                break ;
             case   2 :   // select commission employees in desc order of rate
               query  =   "SELECT * FROM commissionEmployees ORDER BY "   +  
                   "commissionRate DESC" ;
                break ;
             case   3 :   // user defined query
               query  =  input . getText ();
                break ;
          }   // end switch
           
         statement  =  connection . createStatement ();

          if   (  query . substring (   0 ,   6   ). equals (   "SELECT"   )   )
            tableModel . setQuery (  query  );
          else  
            statement . executeUpdate (  query  );
       }   // end try
       catch   (   SQLException  sqlex  )  
       {
         sqlex . printStackTrace ();
       }   // end catch
    }   // end method getTable

    public   static   void  main (   String  args []   )  
    {
       new   DisplayQueryResults ();
    }   // end main
}   // end class DisplayQueryResults


/**************************************************************************
 * (C) Copyright 1992-2012  by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

ch28solutions/ex28_05/ResultSetTableModel.class

                public 
                synchronized 
                class ResultSetTableModel 
                extends javax.swing.table.AbstractTableModel {
    
                private java.sql.Connection 
                connection;
    
                private java.sql.Statement 
                statement;
    
                private java.sql.ResultSet 
                resultSet;
    
                private java.sql.ResultSetMetaData 
                metaData;
    
                private int 
                numberOfRows;
    
                private boolean 
                connectedToDatabase;
    
                public void ResultSetTableModel(String, String, String, String, String) 
                throws java.sql.SQLException, ClassNotFoundException;
    
                public Class 
                getColumnClass(int) 
                throws IllegalStateException;
    
                public int 
                getColumnCount() 
                throws IllegalStateException;
    
                public String 
                getColumnName(int) 
                throws IllegalStateException;
    
                public int 
                getRowCount() 
                throws IllegalStateException;
    
                public Object 
                getValueAt(int, int) 
                throws IllegalStateException;
    
                public void 
                setQuery(String) 
                throws java.sql.SQLException, IllegalStateException;
    
                public void 
                disconnectFromDatabase();
    
                public java.sql.Connection 
                getConnection();
}

            

ch28solutions/ex28_05/ResultSetTableModel.java

ch28solutions/ex28_05/ResultSetTableModel.java

// Exercise 25.4 Solution: ResultSetTableModel.java
// A TableModel that supplies ResultSet data to a JTable.
import  java . sql . Connection ;
import  java . sql . Statement ;
import  java . sql . DriverManager ;
import  java . sql . ResultSet ;
import  java . sql . ResultSetMetaData ;
import  java . sql . SQLException ;
import  javax . swing . table . AbstractTableModel ;

// ResultSet rows and columns are counted from 1 and JTable 
// rows and columns are counted from 0. When processing 
// ResultSet rows or columns for use in a JTable, it is 
// necessary to add 1 to the row or column number to manipulate
// the appropriate ResultSet column (i.e., JTable column 0 is 
// ResultSet column 1 and JTable row 0 is ResultSet row 1).
public   class   ResultSetTableModel   extends   AbstractTableModel  
{
    private   Connection  connection ;
    private   Statement  statement ;
    private   ResultSet  resultSet ;
    private   ResultSetMetaData  metaData ;
    private   int  numberOfRows ;

    // keep track of database connection status 
    private   boolean  connectedToDatabase  =   false ;
   
    // constructor initializes resultSet and obtains its meta data object;
    // determines number of rows
    public   ResultSetTableModel (   String  driver ,   String  url ,  
       String  username ,   String  password ,   String  query  )  
       throws   SQLException ,   ClassNotFoundException
    {
       Class . forName (  driver  );   // load database driver class
      connection  =   DriverManager . getConnection (  url ,  username ,  password  );

       // create Statement to query database   
      statement  =  connection . createStatement (  
          ResultSet . TYPE_SCROLL_INSENSITIVE ,    
          ResultSet . CONCUR_READ_ONLY  );         

      connectedToDatabase  =   true ;   // update database connection status
      setQuery (  query  );   // set query and execute it
    }   // end constructor ResultSetTableModel

    // get class that represents column type
    public   Class  getColumnClass (   int  column  )   throws   IllegalStateException
    {
       // ensure database connection is available                        
       if   (   ! connectedToDatabase  )                                        
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine Java class of column
       try  
       {
          String  className  =  metaData . getColumnClassName (  column  +   1   );
         
          // return Class object that represents className
          return   Class . forName (  className  );               
       }   // end try
       catch   (   Exception  exception  )  
       {
         exception . printStackTrace ();
       }   // end catch
      
       return   Object . class ;   // if problems occur above, assume type Object
    }   // end method getColumnClass

    // get number of columns in ResultSet
    public   int  getColumnCount ()   throws   IllegalStateException
    {    
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine number of columns
       try  
       {
          return  metaData . getColumnCount ();  
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   0 ;   // if problems occur above, return 0 for number of columns
    }   // end method getColumnCount

    // get name of a particular column in ResultSet
    public   String  getColumnName (   int  column  )   throws   IllegalStateException
    {     
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine column name
       try  
       {
          return  metaData . getColumnName (  column  +   1   );   
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   "" ;   // if problems, return empty string for column name
    }   // end method getColumnName

    // return number of rows in ResultSet
    public   int  getRowCount ()   throws   IllegalStateException
    {       
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );
 
       return  numberOfRows ;
    }   // end method getRowCount

    // obtain value in particular row and column
    public   Object  getValueAt (   int  row ,   int  column  )  
       throws   IllegalStateException
    {
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // obtain a value at specified ResultSet row and column
       try  
       {
         resultSet . absolute (  row  +   1   );
          return  resultSet . getObject (  column  +   1   );
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   "" ;   // if problems, return empty string object
    }   // end method getValueAt
   
    // set new database query string
    public   void  setQuery (   String  query  )  
       throws   SQLException ,   IllegalStateException  
    {
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

      resultSet  =  statement . executeQuery (  query  );   // execute query
      metaData  =  resultSet . getMetaData ();   // get metadata

       // determine number of rows in ResultSet
      resultSet . last ();   // move to last row
      numberOfRows  =  resultSet . getRow ();   // get row number      
      fireTableStructureChanged ();   // table model changed
    }   // end method setQuery

    // close Statement and Connection               
    public   void  disconnectFromDatabase ()             
    {                                                
       // close Statement and Connection            
       try                                           
       {                                             
         statement . close ();                         
         connection . close ();                        
       }   // end try                                 
       catch   (   SQLException  sqlException  )           
       {                                             
         sqlException . printStackTrace ();            
       }   // end catch                               
       finally    // update database connection status
       {                                             
         connectedToDatabase  =   false ;               
       }   // end finally                             
    }   // end method disconnectFromDatabase          

    // return Connection
    public   Connection  getConnection ()
    {
       return  connection ;
    }   // end method getConnection
}    // end class ResultSetTableModel





/**************************************************************************
 * (C) Copyright 1992-2012  by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

ch28solutions/ex28_06/DisplayQueryResults$1.class

                synchronized 
                class DisplayQueryResults$1 
                implements java.awt.event.ActionListener {
    void DisplayQueryResults$1(DisplayQueryResults);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_06/DisplayQueryResults$2.class

                synchronized 
                class DisplayQueryResults$2 
                implements java.awt.event.ActionListener {
    void DisplayQueryResults$2(DisplayQueryResults);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_06/DisplayQueryResults$3.class

                synchronized 
                class DisplayQueryResults$3 
                extends java.awt.event.WindowAdapter {
    void DisplayQueryResults$3(DisplayQueryResults);
    
                public void 
                windowClosed(java.awt.event.WindowEvent);
}

            

ch28solutions/ex28_06/DisplayQueryResults.class

                public 
                synchronized 
                class DisplayQueryResults 
                extends javax.swing.JFrame {
    
                static 
                final String 
                JDBC_DRIVER = com.mysql.jdbc.Driver;
    
                static 
                final String 
                DATABASE_URL = jdbc:mysql://localhost/employees;
    
                static 
                final String 
                USERNAME = deitel;
    
                static 
                final String 
                PASSWORD = deitel;
    
                static 
                final String 
                DEFAULT_QUERY = SELECT * FROM employees;
    
                private java.sql.Connection 
                connection;
    
                private java.sql.Statement 
                statement;
    
                private java.sql.ResultSet 
                resultSet;
    
                private ResultSetTableModel 
                tableModel;
    
                private javax.swing.JTable 
                table;
    
                private javax.swing.JComboBox 
                inputQuery;
    
                private javax.swing.JButton 
                submitQuery;
    
                private javax.swing.JTextField 
                input;
    
                public void DisplayQueryResults();
    
                private void 
                getTable();
    
                private void 
                addBirthdayBonus();
    
                private void 
                addBonus(java.util.Vector);
    
                public 
                static void 
                main(String[]);
}

            

ch28solutions/ex28_06/DisplayQueryResults.java

ch28solutions/ex28_06/DisplayQueryResults.java

// Exercise 25.6 Solution: DisplayQueryResults.java
import  java . sql . SQLException ;
import  java . sql . Connection ;
import  java . sql . Statement ;
import  java . sql . ResultSet ;
import  java . awt . FlowLayout ;
import  java . awt . BorderLayout ;
import  java . awt . event . ActionListener ;
import  java . awt . event . ActionEvent ;
import  java . awt . event . WindowAdapter ;
import  java . awt . event . WindowEvent ;
import  java . util . Vector ;
import  javax . swing . JFrame ;
import  javax . swing . JTable ;
import  javax . swing . JComboBox ;
import  javax . swing . JButton ;
import  javax . swing . JTextField ;
import  javax . swing . JScrollPane ;
import  javax . swing . JPanel ;
import  javax . swing . JLabel ;
import  javax . swing . JOptionPane ;

public   class   DisplayQueryResults   extends   JFrame  
{
    // JDBC driver and database URL
    static   final   String  JDBC_DRIVER  =   "com.mysql.jdbc.Driver" ;
    static   final   String  DATABASE_URL  =   "jdbc:mysql://localhost/employees" ;
    static   final   String  USERNAME  =   "deitel" ;
    static   final   String  PASSWORD  =   "deitel" ;

    // default query retrieves all data from employees table
    static   final   String  DEFAULT_QUERY  =   "SELECT * FROM employees" ;

    private   Connection  connection ;
    private   Statement  statement ;
    private   ResultSet  resultSet ;
    private   ResultSetTableModel  tableModel ;
    private   JTable  table ;
    private   JComboBox  inputQuery ;
    private   JButton  submitQuery ;
    private   JTextField  input ;
    
    public   DisplayQueryResults ()  
    {    
       super (   "Select Query. Click Submit to See Results."   );

       // create ResultSetTableModel with default JDBC driver, 
       // database URL and query
       try  
       {
          // create TableModel for results of query SELECT * FROM employees
         tableModel  =   new   ResultSetTableModel (  JDBC_DRIVER ,  DATABASE_URL ,  
            USERNAME ,  PASSWORD ,  DEFAULT_QUERY  );

         connection  =  tableModel . getConnection ();
       }   // end try
       catch   (   ClassNotFoundException  cnfex  )  
       {
          System . err . println (   "Failed to load JDBC driver."   );
         cnfex . printStackTrace ();
          System . exit (   1   );    // terminate program
       }   // end catch
       catch   (   SQLException  sqlex  )  
       {
          System . err . println (   "Unable to connect"   );
         sqlex . printStackTrace ();
          System . exit (   1   );    // terminate program
       }   // end catch

       String  queries []   =   {   "Select all employees working in Department "   +  
          "SALES." ,   "Select hourly employees working over 30 hours." ,  
          "Select all comission employees in descending order of the "   +
          "comission rate." ,   "Increase base salary by 10% for all base "   +  
          "plus comission employees." ,   "If the employee's birthday is "   +  
          "in the current month, add a $100 bonus." ,   "For all comission "   +  
          "employee whose gross sales over 10000, add $100 bonus." ,  
          "Specify particular query"   };

       // set up GUI      
      inputQuery  =   new   JComboBox (  queries  );
      submitQuery  =   new   JButton (   "Submit query"   );
      submitQuery . addActionListener (
          new   ActionListener ()  
          {
             public   void  actionPerformed (   ActionEvent  e  )  
             {
               getTable ();
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

       JPanel  topPanel  =   new   JPanel ();
      input  =   new   JTextField (   40   );
      input . addActionListener (
          new   ActionListener ()  
          {
             public   void  actionPerformed (   ActionEvent  e  )
             {
                // execute query in JTextField
                try  
                {
                   String  query  =  input . getText ();

                   if   (  query . substring (   0 ,   6   ). equalsIgnoreCase (  
                      "SELECT"   )   )
                     tableModel . setQuery (  query  );
                   else  
                     statement . executeUpdate (  query  );          
                }   // end try
                catch   (   SQLException  sqlex  )  
                {
                  sqlex . printStackTrace ();
                }   // end catch
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

       JPanel  centerPanel  =   new   JPanel ();
      centerPanel . setLayout (   new   FlowLayout ()   );
      centerPanel . add (   new   JLabel (   "Enter query:"   )   );
      centerPanel . add (  input  );
      topPanel . setLayout (   new   BorderLayout ()   );
      topPanel . add (  inputQuery ,   BorderLayout . NORTH  );
      topPanel . add (  centerPanel ,   BorderLayout . CENTER  );
      topPanel . add (  submitQuery ,   BorderLayout . SOUTH  );
 
      table  =   new   JTable (  tableModel  );
      setLayout (   new   BorderLayout ()   );
      add (  topPanel ,   BorderLayout . NORTH  );
      add (   new   JScrollPane (  table  ),   BorderLayout . CENTER  );       

      getTable ();

      setSize (   650 ,   200   );
      setVisible (   true   );

       // dispose of window when user quits application (this overrides
       // the default of HIDE_ON_CLOSE)
      setDefaultCloseOperation (  DISPOSE_ON_CLOSE  );
      
       // ensure database connection is closed when user quits application
      addWindowListener (
          new   WindowAdapter ()  
          {
             // disconnect from database and exit when window has closed
             public   void  windowClosed (   WindowEvent  event  )
             {
               tableModel . disconnectFromDatabase ();
                System . exit (   0   );
             }   // end method windowClosed
          }   // end WindowAdapter inner class
       );   // end call to addWindowListener
    }   // end constructor DisplayQueryResult

    // execute query selected from JComboBox
    private   void  getTable ()
    {        
       // define each query
       try  
       {
          int  selection  =  inputQuery . getSelectedIndex ();
          String  query  =   null ;

          switch   (  selection  )  
          {
             case   0 :   // select employees from the SALES department
               query  =   "SELECT * FROM employees WHERE "   +  
                   "departmentName = 'SALES'" ;
                break ;
             case   1 :   // select hourly employees working over 30 hours
               query  =   "SELECT * FROM hourlyEmployees WHERE hours >= 30" ;
                break ;
             case   2 :   // select commission employees in desc order of rate
               query  =   "SELECT * FROM commissionEmployees ORDER BY "   +  
                   "commissionRate DESC" ;
                break ;
             case   3 :   // increase base salary of basePlusCommissionEmployees
               query  =   "UPDATE basePlusCommissionEmployees SET "   +  
                   "baseSalary = baseSalary * 1.1" ;
                break ;
             case   4 :   // employee birthday is current month, add $100 bonus
               addBirthdayBonus ();
                break ;
             case   5 :   // add 100 to comissionEmployee gross sales over 10000
               query  =   "UPDATE commissionEmployees SET "   +  
                   "bonus = bonus + 100.00 WHERE grossSales >= 10000" ;
                break ;
             case   6 :   // user specified query
               query  =  input . getText ();
                break ;
          }   // end switch
           
         statement  =  connection . createStatement ();

          if   (  query  !=   null   )
          {
             if   (  query . substring (   0 ,   6   ). equalsIgnoreCase (   "SELECT"   )   )
               tableModel . setQuery (  query  );
             else  
               statement . executeUpdate (  query  );
          }   // end if
       }   // end try
       catch   (   SQLException  sqlex  )  
       {
         sqlex . printStackTrace ();
       }   // end catch
    }   // end method getTable

    private   void  addBirthdayBonus ()
    {
       // get current month
       int  currentMonth  =   Integer . parseInt (  
          JOptionPane . showInputDialog (   "Current month: "   )   );

       // validate current month
       while   (   ! (  currentMonth  >=   1   &&  currentMonth  <=   12   )   )
         currentMonth  =   Integer . parseInt (
             JOptionPane . showInputDialog (   "Current month: "   )   );
      
       // add $100 bonus to employee whose birthday matches current month
       try  
       {
          String  getEmployees  =   "SELECT * FROM employees" ;
         statement  =  connection . createStatement ();
         resultSet  =  statement . executeQuery (  getEmployees  );          
          String  birthday ;
          Vector <   String   >  birthdayList  =   new   Vector <   String   > ();
 
          // find employee whose birthday match current month
          while   (  resultSet . next ()   )  
          {
            birthday  =  resultSet . getDate (   "birthday"   ). toString ();
             int  month  =   Integer . parseInt (  birthday . substring (   5 ,   7   )   );

             if   (  month  ==  currentMonth  )  
             {
               birthdayList . add (  
                  resultSet . getString (   "socialSecurityNumber"   )   );
               birthdayList . add (
                  resultSet . getString (   "employeeType"   )   +   "s"   );
             }   // end if
          }   // end while

         addBonus (  birthdayList  );
       }   // end try
       catch   (   SQLException  exception  )  
       {
         exception . printStackTrace ();
       }   // end catch
    }    // end addBirthdayBonus

    private   void  addBonus (   Vector <   String   >  vector  )
    {
       String  socialSecurityNumber ,  employeeType ;

       // add bonus to all employees in the vector
       try  
       {
          // add $100 to each employee listed in the vector
          for   (   int  i  =   0 ;  i  <  vector . size ()   /   2 ;  i ++   )  
          {
            socialSecurityNumber  =  vector . elementAt (  i  *   2   );
            employeeType  =  vector . elementAt (  i  *   2   +   1   );

             // add $100 bonus
            statement  =  connection . createStatement ();
            statement . executeUpdate (   "UPDATE "   +  employeeType  +  
                " SET bonus = bonus + 100.00 WHERE socialSecurityNumber "   +
                "= '"   +  socialSecurityNumber  +   "'"   );

             // display after update
            tableModel . setQuery (   "SELECT * FROM "   +  employeeType  );
          }   // end for
       }   // end try
       catch   (   SQLException  exception  )  
       {
         exception . printStackTrace ();
       }   // end catch
    }   // end method addBonus

    public   static   void  main (   String  args []   )  
    {
       new   DisplayQueryResults ();
    }   // end main
}   // end class DisplayQueryResults

/**************************************************************************
 * (C) Copyright 1992-2012  by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

ch28solutions/ex28_06/ResultSetTableModel.class

                public 
                synchronized 
                class ResultSetTableModel 
                extends javax.swing.table.AbstractTableModel {
    
                private java.sql.Connection 
                connection;
    
                private java.sql.Statement 
                statement;
    
                private java.sql.ResultSet 
                resultSet;
    
                private java.sql.ResultSetMetaData 
                metaData;
    
                private int 
                numberOfRows;
    
                private boolean 
                connectedToDatabase;
    
                public void ResultSetTableModel(String, String, String, String, String) 
                throws java.sql.SQLException, ClassNotFoundException;
    
                public Class 
                getColumnClass(int) 
                throws IllegalStateException;
    
                public int 
                getColumnCount() 
                throws IllegalStateException;
    
                public String 
                getColumnName(int) 
                throws IllegalStateException;
    
                public int 
                getRowCount() 
                throws IllegalStateException;
    
                public Object 
                getValueAt(int, int) 
                throws IllegalStateException;
    
                public void 
                setQuery(String) 
                throws java.sql.SQLException, IllegalStateException;
    
                public void 
                disconnectFromDatabase();
    
                public java.sql.Connection 
                getConnection();
}

            

ch28solutions/ex28_06/ResultSetTableModel.java

ch28solutions/ex28_06/ResultSetTableModel.java

// Exercise 25.4 Solution: ResultSetTableModel.java
// A TableModel that supplies ResultSet data to a JTable.
import  java . sql . Connection ;
import  java . sql . Statement ;
import  java . sql . DriverManager ;
import  java . sql . ResultSet ;
import  java . sql . ResultSetMetaData ;
import  java . sql . SQLException ;
import  javax . swing . table . AbstractTableModel ;

// ResultSet rows and columns are counted from 1 and JTable 
// rows and columns are counted from 0. When processing 
// ResultSet rows or columns for use in a JTable, it is 
// necessary to add 1 to the row or column number to manipulate
// the appropriate ResultSet column (i.e., JTable column 0 is 
// ResultSet column 1 and JTable row 0 is ResultSet row 1).
public   class   ResultSetTableModel   extends   AbstractTableModel  
{
    private   Connection  connection ;
    private   Statement  statement ;
    private   ResultSet  resultSet ;
    private   ResultSetMetaData  metaData ;
    private   int  numberOfRows ;

    // keep track of database connection status 
    private   boolean  connectedToDatabase  =   false ;
   
    // constructor initializes resultSet and obtains its meta data object;
    // determines number of rows
    public   ResultSetTableModel (   String  driver ,   String  url ,  
       String  username ,   String  password ,   String  query  )  
       throws   SQLException ,   ClassNotFoundException
    {
       Class . forName (  driver  );   // load database driver class
      connection  =   DriverManager . getConnection (  url ,  username ,  password  );

       // create Statement to query database   
      statement  =  connection . createStatement (  
          ResultSet . TYPE_SCROLL_INSENSITIVE ,    
          ResultSet . CONCUR_READ_ONLY  );         

      connectedToDatabase  =   true ;   // update database connection status
      setQuery (  query  );   // set query and execute it
    }   // end constructor ResultSetTableModel

    // get class that represents column type
    public   Class  getColumnClass (   int  column  )   throws   IllegalStateException
    {
       // ensure database connection is available                        
       if   (   ! connectedToDatabase  )                                        
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine Java class of column
       try  
       {
          String  className  =  metaData . getColumnClassName (  column  +   1   );
         
          // return Class object that represents className
          return   Class . forName (  className  );               
       }   // end try
       catch   (   Exception  exception  )  
       {
         exception . printStackTrace ();
       }   // end catch
      
       return   Object . class ;   // if problems occur above, assume type Object
    }   // end method getColumnClass

    // get number of columns in ResultSet
    public   int  getColumnCount ()   throws   IllegalStateException
    {    
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine number of columns
       try  
       {
          return  metaData . getColumnCount ();  
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   0 ;   // if problems occur above, return 0 for number of columns
    }   // end method getColumnCount

    // get name of a particular column in ResultSet
    public   String  getColumnName (   int  column  )   throws   IllegalStateException
    {     
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // determine column name
       try  
       {
          return  metaData . getColumnName (  column  +   1   );   
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   "" ;   // if problems, return empty string for column name
    }   // end method getColumnName

    // return number of rows in ResultSet
    public   int  getRowCount ()   throws   IllegalStateException
    {       
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );
 
       return  numberOfRows ;
    }   // end method getRowCount

    // obtain value in particular row and column
    public   Object  getValueAt (   int  row ,   int  column  )  
       throws   IllegalStateException
    {
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

       // obtain a value at specified ResultSet row and column
       try  
       {
         resultSet . absolute (  row  +   1   );
          return  resultSet . getObject (  column  +   1   );
       }   // end try
       catch   (   SQLException  sqlException  )  
       {
         sqlException . printStackTrace ();
       }   // end catch
      
       return   "" ;   // if problems, return empty string object
    }   // end method getValueAt
   
    // set new database query string
    public   void  setQuery (   String  query  )  
       throws   SQLException ,   IllegalStateException  
    {
       // ensure database connection is available
       if   (   ! connectedToDatabase  )  
          throw   new   IllegalStateException (   "Not Connected to Database"   );

      resultSet  =  statement . executeQuery (  query  );   // execute query
      metaData  =  resultSet . getMetaData ();   // get metadata

       // determine number of rows in ResultSet
      resultSet . last ();   // move to last row
      numberOfRows  =  resultSet . getRow ();   // get row number      
      fireTableStructureChanged ();   // table model changed
    }   // end method setQuery

    // close Statement and Connection               
    public   void  disconnectFromDatabase ()             
    {                                                
       // close Statement and Connection            
       try                                           
       {                                             
         statement . close ();                         
         connection . close ();                        
       }   // end try                                 
       catch   (   SQLException  sqlException  )           
       {                                             
         sqlException . printStackTrace ();            
       }   // end catch                               
       finally    // update database connection status
       {                                             
         connectedToDatabase  =   false ;               
       }   // end finally                             
    }   // end method disconnectFromDatabase          

    // return Connection
    public   Connection  getConnection ()
    {
       return  connection ;
    }   // end method getConnection
}    // end class ResultSetTableModel





/**************************************************************************
 * (C) Copyright 1992-2012  by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

ch28solutions/ex28_07/address.sql

DROP TABLE Addresses; CREATE TABLE Addresses ( AddressID INT NOT NULL GENERATED ALWAYS AS IDENTITY, FirstName VARCHAR (15) NOT NULL, LastName VARCHAR (30) NOT NULL, Email VARCHAR (30) NOT NULL, PhoneNumber VARCHAR (15) NOT NULL ); INSERT INTO Addresses (FirstName,LastName,Email,PhoneNumber) VALUES ('Mike','Green','[email protected]','555-5555'), ('Mary','Brown','[email protected]','555-1234');

ch28solutions/ex28_07/AddressBook/db.lck

ch28solutions/ex28_07/AddressBook/log/log.ctrl

ch28solutions/ex28_07/AddressBook/log/log1.dat

ch28solutions/ex28_07/AddressBook/log/logmirror.ctrl

ch28solutions/ex28_07/AddressBook/seg0/c10.dat

ch28solutions/ex28_07/AddressBook/seg0/c101.dat

ch28solutions/ex28_07/AddressBook/seg0/c111.dat

ch28solutions/ex28_07/AddressBook/seg0/c121.dat

ch28solutions/ex28_07/AddressBook/seg0/c130.dat

ch28solutions/ex28_07/AddressBook/seg0/c141.dat

ch28solutions/ex28_07/AddressBook/seg0/c150.dat

ch28solutions/ex28_07/AddressBook/seg0/c161.dat

ch28solutions/ex28_07/AddressBook/seg0/c171.dat

ch28solutions/ex28_07/AddressBook/seg0/c180.dat

ch28solutions/ex28_07/AddressBook/seg0/c191.dat

ch28solutions/ex28_07/AddressBook/seg0/c1a1.dat

ch28solutions/ex28_07/AddressBook/seg0/c1b1.dat

ch28solutions/ex28_07/AddressBook/seg0/c1c0.dat

ch28solutions/ex28_07/AddressBook/seg0/c1d1.dat

ch28solutions/ex28_07/AddressBook/seg0/c1e0.dat

ch28solutions/ex28_07/AddressBook/seg0/c1f1.dat

ch28solutions/ex28_07/AddressBook/seg0/c20.dat

ch28solutions/ex28_07/AddressBook/seg0/c200.dat

ch28solutions/ex28_07/AddressBook/seg0/c211.dat

ch28solutions/ex28_07/AddressBook/seg0/c221.dat

ch28solutions/ex28_07/AddressBook/seg0/c230.dat

ch28solutions/ex28_07/AddressBook/seg0/c241.dat

ch28solutions/ex28_07/AddressBook/seg0/c251.dat

ch28solutions/ex28_07/AddressBook/seg0/c260.dat

ch28solutions/ex28_07/AddressBook/seg0/c271.dat

ch28solutions/ex28_07/AddressBook/seg0/c281.dat

ch28solutions/ex28_07/AddressBook/seg0/c290.dat

ch28solutions/ex28_07/AddressBook/seg0/c2a1.dat

ch28solutions/ex28_07/AddressBook/seg0/c2b1.dat

ch28solutions/ex28_07/AddressBook/seg0/c2c1.dat

ch28solutions/ex28_07/AddressBook/seg0/c2d0.dat

ch28solutions/ex28_07/AddressBook/seg0/c2e1.dat

ch28solutions/ex28_07/AddressBook/seg0/c2f0.dat

ch28solutions/ex28_07/AddressBook/seg0/c300.dat

ch28solutions/ex28_07/AddressBook/seg0/c31.dat

ch28solutions/ex28_07/AddressBook/seg0/c311.dat

ch28solutions/ex28_07/AddressBook/seg0/c321.dat

ch28solutions/ex28_07/AddressBook/seg0/c331.dat

ch28solutions/ex28_07/AddressBook/seg0/c340.dat

ch28solutions/ex28_07/AddressBook/seg0/c351.dat

ch28solutions/ex28_07/AddressBook/seg0/c361.dat

ch28solutions/ex28_07/AddressBook/seg0/c371.dat

ch28solutions/ex28_07/AddressBook/seg0/c380.dat

ch28solutions/ex28_07/AddressBook/seg0/c391.dat

ch28solutions/ex28_07/AddressBook/seg0/c3a1.dat

ch28solutions/ex28_07/AddressBook/seg0/c3b1.dat

ch28solutions/ex28_07/AddressBook/seg0/c3c0.dat

ch28solutions/ex28_07/AddressBook/seg0/c41.dat

ch28solutions/ex28_07/AddressBook/seg0/c51.dat

ch28solutions/ex28_07/AddressBook/seg0/c60.dat

ch28solutions/ex28_07/AddressBook/seg0/c71.dat

ch28solutions/ex28_07/AddressBook/seg0/c81.dat

ch28solutions/ex28_07/AddressBook/seg0/c90.dat

ch28solutions/ex28_07/AddressBook/seg0/ca1.dat

ch28solutions/ex28_07/AddressBook/seg0/cb1.dat

ch28solutions/ex28_07/AddressBook/seg0/cc0.dat

ch28solutions/ex28_07/AddressBook/seg0/cd1.dat

ch28solutions/ex28_07/AddressBook/seg0/ce1.dat

ch28solutions/ex28_07/AddressBook/seg0/cf0.dat

ch28solutions/ex28_07/AddressBook/service.properties

#C:\books\2006\jhtp7\solutions\ch25solutions_JDBC\ex25_07\AddressBook # ******************************************************************** # *** Please do NOT edit this file. *** # *** CHANGING THE CONTENT OF THIS FILE MAY CAUSE DATA CORRUPTION. *** # ******************************************************************** #Thu Apr 26 17:47:58 EDT 2007 SysschemasIndex2Identifier=225 SyscolumnsIdentifier=144 SysconglomeratesIndex1Identifier=49 SysconglomeratesIdentifier=32 SyscolumnsIndex2Identifier=177 SysschemasIndex1Identifier=209 SysconglomeratesIndex3Identifier=81 SystablesIndex2Identifier=129 SyscolumnsIndex1Identifier=161 derby.serviceProtocol=org.apache.derby.database.Database SysschemasIdentifier=192 derby.storage.propertiesId=16 SysconglomeratesIndex2Identifier=65 derby.serviceLocale=en_US SystablesIdentifier=96 SystablesIndex1Identifier=113

ch28solutions/ex28_07/AddressBookDisplay$1.class

                synchronized 
                class AddressBookDisplay$1 
                implements java.awt.event.ActionListener {
    void AddressBookDisplay$1(AddressBookDisplay);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_07/AddressBookDisplay$2.class

                synchronized 
                class AddressBookDisplay$2 
                implements java.awt.event.ActionListener {
    void AddressBookDisplay$2(AddressBookDisplay);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_07/AddressBookDisplay$3.class

                synchronized 
                class AddressBookDisplay$3 
                implements java.awt.event.ActionListener {
    void AddressBookDisplay$3(AddressBookDisplay);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_07/AddressBookDisplay$4.class

                synchronized 
                class AddressBookDisplay$4 
                implements java.awt.event.ActionListener {
    void AddressBookDisplay$4(AddressBookDisplay);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_07/AddressBookDisplay$5.class

                synchronized 
                class AddressBookDisplay$5 
                implements java.awt.event.ActionListener {
    void AddressBookDisplay$5(AddressBookDisplay);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_07/AddressBookDisplay$6.class

                synchronized 
                class AddressBookDisplay$6 
                implements java.awt.event.ActionListener {
    void AddressBookDisplay$6(AddressBookDisplay);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_07/AddressBookDisplay$7.class

                synchronized 
                class AddressBookDisplay$7 
                implements java.awt.event.ActionListener {
    void AddressBookDisplay$7(AddressBookDisplay);
    
                public void 
                actionPerformed(java.awt.event.ActionEvent);
}

            

ch28solutions/ex28_07/AddressBookDisplay$8.class

                synchronized 
                class AddressBookDisplay$8 
                extends java.awt.event.WindowAdapter {
    void AddressBookDisplay$8(AddressBookDisplay);
    
                public void 
                windowClosing(java.awt.event.WindowEvent);
}

            

ch28solutions/ex28_07/AddressBookDisplay.class

                public 
                synchronized 
                class AddressBookDisplay 
                extends javax.swing.JFrame {
    
                private Person 
                currentEntry;
    
                private PersonQueries 
                personQueries;
    
                private java.util.List 
                results;
    
                private int 
                numberOfEntries;
    
                private int 
                currentEntryIndex;
    
                private javax.swing.JButton 
                browseButton;
    
                private javax.swing.JLabel 
                emailLabel;
    
                private javax.swing.JTextField 
                emailTextField;
    
                private javax.swing.JLabel 
                firstNameLabel;
    
                private javax.swing.JTextField 
                firstNameTextField;
    
                private javax.swing.JLabel 
                idLabel;
    
                private javax.swing.JTextField 
                idTextField;
    
                private javax.swing.JTextField 
                indexTextField;
    
                private javax.swing.JLabel 
                lastNameLabel;
    
                private javax.swing.JTextField 
                lastNameTextField;
    
                private javax.swing.JTextField 
                maxTextField;
    
                private javax.swing.JButton 
                nextButton;
    
                private javax.swing.JLabel 
                ofLabel;
    
                private javax.swing.JLabel 
                phoneLabel;
    
                private javax.swing.JTextField 
                phoneTextField;
    
                private javax.swing.JButton 
                previousButton;
    
                private javax.swing.JButton 
                queryButton;
    
                private javax.swing.JLabel 
                queryLabel;
    
                private javax.swing.JPanel 
                queryPanel;
    
                private javax.swing.JPanel 
                navigatePanel;
    
                private javax.swing.JPanel 
                displayPanel;
    
                private javax.swing.JTextField 
                queryTextField;
    
                private javax.swing.JButton 
                insertButton;
    
                private javax.swing.JButton 
                updateButton;
    
                public void AddressBookDisplay();
    
                private void 
                previousButtonActionPerformed(java.awt.event.ActionEvent);
    
                private void 
                nextButtonActionPerformed(java.awt.event.ActionEvent);
    
                private void 
                queryButtonActionPerformed(java.awt.event.ActionEvent);
    
                private void 
                indexTextFieldActionPerformed(java.awt.event.ActionEvent);
    
                private void 
                browseButtonActionPerformed(java.awt.event.ActionEvent);
    
                private void 
                insertButtonActionPerformed(java.awt.event.ActionEvent);
    
                private void 
                updateButtonActionPerformed(java.awt.event.ActionEvent);
    
                public 
                static void 
                main(String[]);
}

            

ch28solutions/ex28_07/AddressBookDisplay.java

ch28solutions/ex28_07/AddressBookDisplay.java

// Fig. 25.33: AddressBookDisplay.java
// A simple address book
import  java . awt . event . ActionEvent ;
import  java . awt . event . ActionListener ;
import  java . awt . event . WindowAdapter ;
import  java . awt . event . WindowEvent ;
import  java . awt . FlowLayout ;
import  java . awt . GridLayout ;
import  java . util . List ;  
import  javax . swing . JButton ;
import  javax . swing . Box ;
import  javax . swing . JFrame ;
import  javax . swing . JLabel ;
import  javax . swing . JPanel ;
import  javax . swing . JTextField ;
import  javax . swing . WindowConstants ;
import  javax . swing . BoxLayout ;
import  javax . swing . BorderFactory ;
import  javax . swing . JOptionPane ;

public   class   AddressBookDisplay   extends   JFrame
{
    private   Person  currentEntry ;
    private   PersonQueries  personQueries ;
    private   List <   Person   >  results ;    
    private   int  numberOfEntries  =   0 ;
    private   int  currentEntryIndex ;

    private   JButton  browseButton ;
    private   JLabel  emailLabel ;
    private   JTextField  emailTextField ;
    private   JLabel  firstNameLabel ;
    private   JTextField  firstNameTextField ;
    private   JLabel  idLabel ;
    private   JTextField  idTextField ;
    private   JTextField  indexTextField ;
    private   JLabel  lastNameLabel ;
    private   JTextField  lastNameTextField ;
    private   JTextField  maxTextField ;
    private   JButton  nextButton ;
    private   JLabel  ofLabel ;
    private   JLabel  phoneLabel ;
    private   JTextField  phoneTextField ;
    private   JButton  previousButton ;
    private   JButton  queryButton ;
    private   JLabel  queryLabel ;
    private   JPanel  queryPanel ;
    private   JPanel  navigatePanel ;
    private   JPanel  displayPanel ;
    private   JTextField  queryTextField ;
    private   JButton  insertButton ;
    private   JButton  updateButton ;

    // no-argument constructor
    public   AddressBookDisplay ()
    {
       super (   "Address Book"   );  
      
       // establish database connection and set up PreparedStatements
      personQueries  =   new   PersonQueries ();  
      
       // create GUI
      navigatePanel  =   new   JPanel ();
      previousButton  =   new   JButton ();
      indexTextField  =   new   JTextField (   2   );
      ofLabel  =   new   JLabel ();
      maxTextField  =   new   JTextField (   2   );
      nextButton  =   new   JButton ();
      displayPanel  =   new   JPanel ();
      idLabel  =   new   JLabel ();
      idTextField  =   new   JTextField (   10   );
      firstNameLabel  =   new   JLabel ();
      firstNameTextField  =   new   JTextField (   10   );
      lastNameLabel  =   new   JLabel ();
      lastNameTextField  =   new   JTextField (   10   );
      emailLabel  =   new   JLabel ();
      emailTextField  =   new   JTextField (   10   );
      phoneLabel  =   new   JLabel ();
      phoneTextField  =   new   JTextField (   10   );
      queryPanel  =   new   JPanel ();
      queryLabel  =   new   JLabel ();
      queryTextField  =   new   JTextField (   10   );
      queryButton  =   new   JButton ();
      browseButton  =   new   JButton ();
      insertButton  =   new   JButton ();
      updateButton  =   new   JButton ();

      setLayout (   new   FlowLayout (   FlowLayout . CENTER ,   10 ,   10   )   );
      setSize (   400 ,   325   );
      setResizable (   false   );

      navigatePanel . setLayout (
          new   BoxLayout (  navigatePanel ,   BoxLayout . X_AXIS  )   );

      previousButton . setText (   "Previous"   );
      previousButton . setEnabled (   false   );
      previousButton . addActionListener (
          new   ActionListener ()
          {
             public   void  actionPerformed (   ActionEvent  evt  )
             {
               previousButtonActionPerformed (  evt  );
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

      navigatePanel . add (  previousButton  );
      navigatePanel . add (   Box . createHorizontalStrut (   10   )   );

      indexTextField . setHorizontalAlignment (
          JTextField . CENTER  );
      indexTextField . addActionListener (
          new   ActionListener ()
          {
             public   void  actionPerformed (   ActionEvent  evt  )
             {
               indexTextFieldActionPerformed (  evt  );
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

      navigatePanel . add (  indexTextField  );
      navigatePanel . add (   Box . createHorizontalStrut (   10   )   );

      ofLabel . setText (   "of"   );
      navigatePanel . add (  ofLabel  );
      navigatePanel . add (   Box . createHorizontalStrut (   10   )   );

      maxTextField . setHorizontalAlignment (
          JTextField . CENTER  );
      maxTextField . setEditable (   false   );
      navigatePanel . add (  maxTextField  );
      navigatePanel . add (   Box . createHorizontalStrut (   10   )   );

      nextButton . setText (   "Next"   );
      nextButton . setEnabled (   false   );
      nextButton . addActionListener (
          new   ActionListener ()
          {
             public   void  actionPerformed (   ActionEvent  evt  )
             {
               nextButtonActionPerformed (  evt  );
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

      navigatePanel . add (  nextButton  );
      add (  navigatePanel  );

      displayPanel . setLayout (   new   GridLayout (   5 ,   2 ,   4 ,   4   )   );

      idLabel . setText (   "Address ID:"   );
      displayPanel . add (  idLabel  );

      idTextField . setEditable (   false   );
      displayPanel . add (  idTextField  );

      firstNameLabel . setText (   "First Name:"   );
      displayPanel . add (  firstNameLabel  );
      displayPanel . add (  firstNameTextField  );

      lastNameLabel . setText (   "Last Name:"   );
      displayPanel . add (  lastNameLabel  );
      displayPanel . add (  lastNameTextField  );

      emailLabel . setText (   "Email:"   );
      displayPanel . add (  emailLabel  );
      displayPanel . add (  emailTextField  );

      phoneLabel . setText (   "Phone Number:"   );
      displayPanel . add (  phoneLabel  );
      displayPanel . add (  phoneTextField  );
      add (  displayPanel  );

      queryPanel . setLayout (  
          new   BoxLayout (  queryPanel ,   BoxLayout . X_AXIS )   );

      queryPanel . setBorder (   BorderFactory . createTitledBorder (
          "Find an entry by last name"   )   );
      queryLabel . setText (   "Last Name:"   );
      queryPanel . add (   Box . createHorizontalStrut (   5   )   );
      queryPanel . add (  queryLabel  );
      queryPanel . add (   Box . createHorizontalStrut (   10   )   );
      queryPanel . add (  queryTextField  );
      queryPanel . add (   Box . createHorizontalStrut (   10   )   );

      queryButton . setText (   "Find"   );
      queryButton . addActionListener (
          new   ActionListener ()
          {
             public   void  actionPerformed (   ActionEvent  evt  )
             {
               queryButtonActionPerformed (  evt  );
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

      queryPanel . add (  queryButton  );
      queryPanel . add (   Box . createHorizontalStrut (   5   )   );
      add (  queryPanel  );

      browseButton . setText (   "Browse All Entries"   );
      browseButton . addActionListener (
          new   ActionListener ()
          {
             public   void  actionPerformed (   ActionEvent  evt  )
             {
               browseButtonActionPerformed (  evt  );
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

      add (  browseButton  );

      insertButton . setText (   "Insert New Entry"   );
      insertButton . addActionListener (
          new   ActionListener ()
          {
             public   void  actionPerformed (   ActionEvent  evt  )
             {
               insertButtonActionPerformed (  evt  );
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

       add (  insertButton  );

      updateButton . setText (   "Update Entry"   );
      updateButton . addActionListener (
          new   ActionListener ()
          {
             public   void  actionPerformed (   ActionEvent  evt  )
             {
               updateButtonActionPerformed (  evt  );
             }   // end method actionPerformed
          }   // end anonymous inner class
       );   // end call to addActionListener

      add (  updateButton  );
    
      addWindowListener (  
          new   WindowAdapter ()  
          {   
             public   void  windowClosing (   WindowEvent  evt  )
             {
               personQueries . close ();   // close database connection
                System . exit (   0   );
             }   // end method windowClosing
          }   // end anonymous inner class
       );   // end call to addWindowListener
    
      setVisible (   true   );
    }   // end no-argument constructor

    // handles call when previousButton is clicked
    private   void  previousButtonActionPerformed (   ActionEvent  evt  )
    {
      currentEntryIndex -- ;
      
       if   (  currentEntryIndex  <   0   )
         currentEntryIndex  =  numberOfEntries  -   1 ;
      
      indexTextField . setText (   ""   +   (  currentEntryIndex  +   1   )   );
      indexTextFieldActionPerformed (  evt  );   
    }   // end method previousButtonActionPerformed

    // handles call when nextButton is clicked
    private   void  nextButtonActionPerformed (   ActionEvent  evt  )  
    {
      currentEntryIndex ++ ;
      
       if   (  currentEntryIndex  >=  numberOfEntries  )
         currentEntryIndex  =   0 ;
      
      indexTextField . setText (   ""   +   (  currentEntryIndex  +   1   )   );
      indexTextFieldActionPerformed (  evt  );
    }   // end method nextButtonActionPerformed

    // handles call when queryButton is clicked
    private   void  queryButtonActionPerformed (   ActionEvent  evt  )
    {
      results  =  
         personQueries . getPeopleByLastName (  queryTextField . getText ()   );
      numberOfEntries  =  results . size ();
      
       if   (  numberOfEntries  !=   0   )
       {
         currentEntryIndex  =   0 ;
         currentEntry  =  results . get (  currentEntryIndex  );
         idTextField . setText ( ""   +  currentEntry . getAddressID ()   );
         firstNameTextField . setText (  currentEntry . getFirstName ()   );
         lastNameTextField . setText (  currentEntry . getLastName ()   );
         emailTextField . setText (  currentEntry . getEmail ()   );
         phoneTextField . setText (  currentEntry . getPhoneNumber ()   );
         maxTextField . setText (   ""   +  numberOfEntries  );
         indexTextField . setText (   ""   +   (  currentEntryIndex  +   1   )   );
         nextButton . setEnabled (   true   );
         previousButton . setEnabled (   true   );
       }   // end if
       else
         browseButtonActionPerformed (  evt  );
    }   // end method queryButtonActionPerformed

    // handles call when a new value is entered in indextTextField
    private   void  indexTextFieldActionPerformed (   ActionEvent  evt  )
    {
      currentEntryIndex  =  
          (   Integer . parseInt (  indexTextField . getText ()   )   -   1   );
      
       if   (  numberOfEntries  !=   0   &&  currentEntryIndex  <  numberOfEntries  )
       {
         currentEntry  =  results . get (  currentEntryIndex  );
         idTextField . setText ( ""   +  currentEntry . getAddressID ()   );
         firstNameTextField . setText (  currentEntry . getFirstName ()   );
         lastNameTextField . setText (  currentEntry . getLastName ()   );
         emailTextField . setText (  currentEntry . getEmail ()   );
         phoneTextField . setText (  currentEntry . getPhoneNumber ()   );
         maxTextField . setText (   ""   +  numberOfEntries  );
         indexTextField . setText (   ""   +   (  currentEntryIndex  +   1   )   );
       }   // end if
     }   // end method indexTextFieldActionPerformed

    // handles call when browseButton is clicked
    private   void  browseButtonActionPerformed (   ActionEvent  evt  )
    {
       try
       {
         results  =  personQueries . getAllPeople ();
         numberOfEntries  =  results . size ();
      
          if   (  numberOfEntries  !=   0   )
          {
            currentEntryIndex  =   0 ;
            currentEntry  =  results . get (  currentEntryIndex  );
            idTextField . setText ( ""   +  currentEntry . getAddressID ()   );
            firstNameTextField . setText (  currentEntry . getFirstName ()   );
            lastNameTextField . setText (  currentEntry . getLastName ()   );
            emailTextField . setText (  currentEntry . getEmail ()   );
            phoneTextField . setText (  currentEntry . getPhoneNumber ()   );
            maxTextField . setText (   ""   +  numberOfEntries  );
            indexTextField . setText (   ""   +   (  currentEntryIndex  +   1   )   );
            nextButton . setEnabled (   true   );
            previousButton . setEnabled (   true   );
          }   // end if
       }   // end try
       catch   (   Exception  e  )
       {
         e . printStackTrace ();
       }   // end catch
    }   // end method browseButtonActionPerformed

    // handles call when insertButton is clicked
    private   void  insertButtonActionPerformed (   ActionEvent  evt  )  
    {
       int  result  =  personQueries . addPerson (  firstNameTextField . getText (),
         lastNameTextField . getText (),  emailTextField . getText (),
         phoneTextField . getText ()   );
      
       if   (  result  ==   1   )
          JOptionPane . showMessageDialog (   this ,   "Person added!" ,
             "Person added" ,   JOptionPane . PLAIN_MESSAGE  );
       else
          JOptionPane . showMessageDialog (   this ,   "Person not added!" ,
             "Error" ,   JOptionPane . PLAIN_MESSAGE  );
          
      browseButtonActionPerformed (  evt  );
    }   // end method insertButtonActionPerformed
   
    // handles call when updateButton is clicked
    private   void  updateButtonActionPerformed (   ActionEvent  evt  )  
    {
      personQueries . updatePerson (   Integer . parseInt (
        idTextField . getText ()   ),  firstNameTextField . getText (),
        lastNameTextField . getText (),  emailTextField . getText (),
        phoneTextField . getText ()   );
      browseButtonActionPerformed (  evt  );   
    }   // end method updateButtonActionPerformed
   
    // main method
    public   static   void  main (   String  args []   )
    {
       new   AddressBookDisplay ();
    }   // end method main
}   // end class AddressBookDisplay


/**************************************************************************
 * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

 

ch28solutions/ex28_07/old/Person.java

ch28solutions/ex28_07/old/Person.java

// Fig. X.X: Person.java
// Represents an entry into an address book.

public   class   Person
{
    public   int  addressID ;
    public   String  firstName ;
    public   String  lastName ;
    public   String  email ;
    public   String  phoneNumber ;
}   // end class Person


/**************************************************************************
 * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

 

ch28solutions/ex28_07/old/PersonQueries.java

ch28solutions/ex28_07/old/PersonQueries.java

// Exercise 25.7 Solution: PersonQueries.java
import  java . sql . BaseQuery ;
import  java . sql . Select ;
import  java . sql . Update ;
import  java . sql . DataSet ;

public   interface   PersonQueries   extends   BaseQuery
{
    // Select all of the address
   @ Select (  sql  =   "SELECT * FROM Addresses" ,  scrollable  =   true   )
    DataSet <   Person   >  getAllPeople ();
   
    // Select person by last name
   @ Select (  sql  =   "SELECT * FROM Addresses "   +
       "WHERE LastName = ?1" ,  scrollable  =   true   )
    DataSet <   Person   >  getPeopleByName (   String  name  );
   
    // Add an entry
   @ Update (  sql  =   "INSERT INTO Addresses "   +
    "( FirstName, LastName, Email, PhoneNumber ) "   +
    "VALUES ( ?1, ?2, ?3, ?4 ) "   )
    int  addPerson (   String  fname ,   String  lname ,   String  email ,   String  num  );

    // Update an entry
   @ Update (  sql  =   "UPDATE Addresses SET FirstName = ?2, "   +
    "LastName = ?3, Email = ?4, PhoneNumber = ?5 WHERE AddressID =?1"   )
    int  updatePerson (
       int  id ,   String  fname ,   String  lname ,   String  email ,   String  num );
}   // end interface PersonQueries

/**************************************************************************
 * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

 

ch28solutions/ex28_07/Person.class

                public 
                synchronized 
                class Person {
    
                private int 
                addressID;
    
                private String 
                firstName;
    
                private String 
                lastName;
    
                private String 
                email;
    
                private String 
                phoneNumber;
    
                public void Person();
    
                public void Person(int, String, String, String, String);
    
                public void 
                setAddressID(int);
    
                public int 
                getAddressID();
    
                public void 
                setFirstName(String);
    
                public String 
                getFirstName();
    
                public void 
                setLastName(String);
    
                public String 
                getLastName();
    
                public void 
                setEmail(String);
    
                public String 
                getEmail();
    
                public void 
                setPhoneNumber(String);
    
                public String 
                getPhoneNumber();
}

            

ch28solutions/ex28_07/Person.java

ch28solutions/ex28_07/Person.java

// Fig. 25.31: Person.java
// Person class that represents an entry in an address book.
public   class   Person
{
    private   int  addressID ;
    private   String  firstName ;
    private   String  lastName ;
    private   String  email ;
    private   String  phoneNumber ;

    // no-argument constructor
    public   Person ()
    {
    }   // end no-argument Person constructor

    // constructor
    public   Person (   int  id ,   String  first ,   String  last ,  
       String  emailAddress ,   String  phone  )
    {
      setAddressID (  id  );
      setFirstName (  first  );
      setLastName (  last  );
      setEmail (  emailAddress  );
      setPhoneNumber (  phone  );
    }   // end five-argument Person constructor 

    // sets the addressID
    public   void  setAddressID (   int  id  )
    {
      addressID  =  id ;
    }   // end method setAddressID

    // returns the addressID 
    public   int  getAddressID ()
    {
       return  addressID ;
    }   // end method getAddressID
   
    // sets the firstName
    public   void  setFirstName (   String  first  )
    {
      firstName  =  first ;
    }   // end method setFirstName

    // returns the first name 
    public   String  getFirstName ()
    {
       return  firstName ;
    }   // end method getFirstName
   
    // sets the lastName
    public   void  setLastName (   String  last  )
    {
      lastName  =  last ;
    }   // end method setLastName

    // returns the first name 
    public   String  getLastName ()
    {
       return  lastName ;
    }   // end method getLastName
   
    // sets the email address
    public   void  setEmail (   String  emailAddress  )
    {
      email  =  emailAddress ;
    }   // end method setEmail

    // returns the email address
    public   String  getEmail ()
    {
       return  email ;
    }   // end method getEmail
   
    // sets the phone number
    public   void  setPhoneNumber (   String  phone  )
    {
      phoneNumber  =  phone ;
    }   // end method setPhoneNumber

    // returns the email address
    public   String  getPhoneNumber ()
    {
       return  phoneNumber ;
    }   // end method getPhoneNumber
}   // end class Person


/**************************************************************************
 * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

 

ch28solutions/ex28_07/PersonQueries.class

                public 
                synchronized 
                class PersonQueries {
    
                private 
                static 
                final String 
                URL = jdbc:derby:AddressBook;
    
                private 
                static 
                final String 
                USERNAME = deitel;
    
                private 
                static 
                final String 
                PASSWORD = deitel;
    
                private java.sql.Connection 
                connection;
    
                private java.sql.PreparedStatement 
                selectAllPeople;
    
                private java.sql.PreparedStatement 
                selectPeopleByLastName;
    
                private java.sql.PreparedStatement 
                insertNewPerson;
    
                private java.sql.PreparedStatement 
                updateExistingPerson;
    
                public void PersonQueries();
    
                public java.util.List 
                getAllPeople();
    
                public java.util.List 
                getPeopleByLastName(String);
    
                public int 
                addPerson(String, String, String, String);
    
                public int 
                updatePerson(int, String, String, String, String);
    
                public void 
                close();
}

            

ch28solutions/ex28_07/PersonQueries.java

ch28solutions/ex28_07/PersonQueries.java

// Exercise 25.7: PersonQueries.java
// PreparedStatements used by the Address Book application
import  java . sql . Connection ;
import  java . sql . DriverManager ;
import  java . sql . PreparedStatement ;
import  java . sql . ResultSet ;
import  java . sql . SQLException ;
import  java . util . List ;
import  java . util . ArrayList ;

public   class   PersonQueries  
{
    private   static   final   String  URL  =   "jdbc:derby:AddressBook" ;
    private   static   final   String  USERNAME  =   "deitel" ;
    private   static   final   String  PASSWORD  =   "deitel" ;

    private   Connection  connection  =   null ;   // manages connection
    private   PreparedStatement  selectAllPeople  =   null ;  
    private   PreparedStatement  selectPeopleByLastName  =   null ;  
    private   PreparedStatement  insertNewPerson  =   null ;  
    private   PreparedStatement  updateExistingPerson  =   null ;  
    
    // constructor
    public   PersonQueries ()
    {
       try  
       {
         connection  =  
             DriverManager . getConnection (  URL ,  USERNAME ,  PASSWORD  );

          // create query that selects all entries in the AddressBook
         selectAllPeople  =  
            connection . prepareStatement (   "SELECT * FROM Addresses"   );
         
          // create query that selects entries with a specific last name
         selectPeopleByLastName  =  connection . prepareStatement (  
             "SELECT * FROM Addresses WHERE LastName = ?"   );
         
          // create insert that adds a new entry into the database
         insertNewPerson  =  connection . prepareStatement (  
             "INSERT INTO Addresses "   +  
             "( FirstName, LastName, Email, PhoneNumber ) "   +  
             "VALUES ( ?, ?, ?, ? )"   );

         updateExistingPerson  =  connection . prepareStatement (
             "UPDATE Addresses SET FirstName = ?, LastName = ?, "   +
             "Email = ?, PhoneNumber = ? WHERE AddressID = ?"   );

       }   // end try
       catch   (   SQLException  sqlException  )
       {
         sqlException . printStackTrace ();
          System . exit (   1   );
       }   // end catch
    }   // end PersonQueries constructor
   
    // select all of the addresses in the database
    public   List <   Person   >  getAllPeople ()
    {
       List <   Person   >  results  =   null ;
       ResultSet  resultSet  =   null ;
      
       try  
       {
          // executeQuery returns ResultSet containing matching entries
         resultSet  =  selectAllPeople . executeQuery ();  
         results  =   new   ArrayList <   Person   > ();
         
          while   (  resultSet . next ()   )
          {
            results . add (   new   Person (
               resultSet . getInt (   "addressID"   ),
               resultSet . getString (   "firstName"   ),
               resultSet . getString (   "lastName"   ),
               resultSet . getString (   "email"   ),
               resultSet . getString (   "phoneNumber"   )   )   );
          }   // end while
       }   // end try
       catch   (   SQLException  sqlException  )
       {
         sqlException . printStackTrace ();          
       }   // end catch
       finally
       {
          try  
          {
            resultSet . close ();
          }   // end try
          catch   (   SQLException  sqlException  )
          {
            sqlException . printStackTrace ();          
            close ();
          }   // end catch
       }   // end finally
      
       return  results ;
    }   // end method getAllPeople
   
    // select person by last name
   
    public   List <   Person   >  getPeopleByLastName (   String  name  )
    {
       List <   Person   >  results  =   null ;
       ResultSet  resultSet  =   null ;

       try  
       {
         selectPeopleByLastName . setString (   1 ,  name  );   // specify last name

          // executeQuery returns ResultSet containing matching entries
         resultSet  =  selectPeopleByLastName . executeQuery ();  

         results  =   new   ArrayList <   Person   > ();

          while   (  resultSet . next ()   )
          {
            results . add (   new   Person (
               resultSet . getInt (   "addressID"   ),
               resultSet . getString (   "firstName"   ),
               resultSet . getString (   "lastName"   ),
               resultSet . getString (   "email"   ),
               resultSet . getString (   "phoneNumber"   )   )   );
          }   // end while
       }   // end try
       catch   (   SQLException  sqlException  )
       {
         sqlException . printStackTrace ();
       }   // end catch
       finally
       {
          try  
          {
            resultSet . close ();
          }   // end try
          catch   (   SQLException  sqlException  )
          {
            sqlException . printStackTrace ();          
            close ();
          }   // end catch
       }   // end finally
      
       return  results ;
    }   // end method getPeopleByName
   
    // add an entry
    public   int  addPerson (  
       String  fname ,   String  lname ,   String  email ,   String  num  )
    {
       int  result  =   0 ;
      
       // set parameters, then execute insertNewPerson
       try  
       {
         insertNewPerson . setString (   1 ,  fname  );
         insertNewPerson . setString (   2 ,  lname  );
         insertNewPerson . setString (   3 ,  email  );
         insertNewPerson . setString (   4 ,  num  );

          // insert the new entry; returns # of rows updated
         result  =  insertNewPerson . executeUpdate ();  
       }   // end try
       catch   (   SQLException  sqlException  )
       {
         sqlException . printStackTrace ();
         close ();
       }   // end catch
      
       return  result ;
    }   // end method addPerson
   
    // update an entry
    public   int  updatePerson (  
       int  id ,   String  fname ,   String  lname ,   String  email ,   String  num  )
    {
       int  result  =   0 ;
      
       // set parameters, then execute insertNewPerson
       try  
       {
         updateExistingPerson . setString (   1 ,  fname  );
         updateExistingPerson . setString (   2 ,  lname  );
         updateExistingPerson . setString (   3 ,  email  );
         updateExistingPerson . setString (   4 ,  num  );
         updateExistingPerson . setInt (   5 ,  id  );

          // update an entry; returns # of rows updated
         result  =  updateExistingPerson . executeUpdate ();  
       }   // end try
       catch   (   SQLException  sqlException  )
       {
         sqlException . printStackTrace ();
         close ();
       }   // end catch
      
       return  result ;
    }   // end method updatePerson
   
    // close the database connection
    public   void  close ()
    {
       try  
       {
         connection . close ();
       }   // end try
       catch   (   SQLException  sqlException  )
       {
         sqlException . printStackTrace ();
       }   // end catch
    }   // end method close
}   // end interface PersonQueries


/**************************************************************************
 * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. 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.                     *
 *************************************************************************/

 

ch28solutions/SQLscripts/java db/address.sql

DROP TABLE Addresses; CREATE TABLE Addresses ( AddressID INT NOT NULL GENERATED ALWAYS AS IDENTITY, FirstName VARCHAR (15) NOT NULL, LastName VARCHAR (30) NOT NULL, Email VARCHAR (30) NOT NULL, PhoneNumber VARCHAR (15) NOT NULL ); INSERT INTO Addresses (FirstName,LastName,Email,PhoneNumber) VALUES ('Mike','Green','[email protected]','555-5555'), ('Mary','Brown','[email protected]','555-1234');

ch28solutions/SQLscripts/java db/books.sql

DROP TABLE "authorISBN"; DROP TABLE "titles"; DROP TABLE "authors"; CREATE TABLE "authors" ( "authorID" INT NOT NULL GENERATED ALWAYS AS IDENTITY, "firstName" varchar (20) NOT NULL, "lastName" varchar (30) NOT NULL, PRIMARY KEY ("authorID") ); CREATE TABLE "titles" ( "isbn" varchar (20) NOT NULL, "title" varchar (100) NOT NULL, "editionNumber" INT NOT NULL, "copyright" varchar (4) NOT NULL, PRIMARY KEY ("isbn") ); CREATE TABLE "authorISBN" ( "authorID" INT NOT NULL, "isbn" varchar (20) NOT NULL, FOREIGN KEY ("authorID") REFERENCES "authors" ("authorID"), FOREIGN KEY ("isbn") REFERENCES "titles" ("isbn") ); INSERT INTO "authors" ("firstName", "lastName") VALUES ('Harvey','Deitel'), ('Paul','Deitel'), ('Andrew','Goldberg'), ('David','Choffnes'); INSERT INTO "titles" ("isbn","title","editionNumber", "copyright") VALUES ('0131869000','Visual Basic 2005 How to Program',3,'2006'), ('0131525239','Visual C# 2005 How to Program',2,'2006'), ('0132222205','Java How to Program',7,'2007'), ('0131857576','C++ How to Program',5,'2005'), ('0132404168','C How to Program',5,'2007'), ('0131450913','Internet & World Wide Web How to Program',3,'2004'), ('0131828274','Operating Systems',3,'2004'); INSERT INTO "authorISBN" ("authorID","isbn") VALUES (1,'0131869000'), (2,'0131869000'), (1,'0131525239'), (2,'0131525239'), (1,'0132222205'), (2,'0132222205'), (1,'0131857576'), (2,'0131857576'), (1,'0132404168'), (2,'0132404168'), (1,'0131450913'), (2,'0131450913'), (3,'0131450913'), (1,'0131828274'), (2,'0131828274'), (4,'0131828274');

ch28solutions/SQLscripts/mysql/Books.sql

DROP DATABASE IF EXISTS books; CREATE DATABASE books; USE books; CREATE TABLE Authors ( AuthorID int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(30) NOT NULL, LastName varchar(30) NOT NULL ) ; CREATE TABLE Titles ( ISBN varchar(20) NOT NULL PRIMARY KEY, Title varchar(100) NOT NULL, EditionNumber int NOT NULL, Copyright varchar(4) NOT NULL ) ; CREATE TABLE AuthorISBN ( AuthorID int NOT NULL, ISBN varchar(20) NOT NULL, FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID), FOREIGN KEY (ISBN) References Titles(ISBN) ) ; INSERT INTO Authors (FirstName,LastName) VALUES ('Harvey','Deitel') ; INSERT INTO Authors (FirstName,LastName) VALUES ('Paul','Deitel') ; INSERT INTO Authors (FirstName,LastName) VALUES ('Andrew','Goldberg') ; INSERT INTO Authors (FirstName,LastName) VALUES ('David','Choffnes') ; INSERT INTO Titles (ISBN,Title,EditionNumber,Copyright) VALUES ('0131869000','Visual Basic 2005 How to Program',3,'2006') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (1,'0131869000') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (2,'0131869000') ; INSERT INTO Titles (ISBN,Title,EditionNumber,Copyright) VALUES ('0131525239','Visual C# 2005 How to Program',2,'2006') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (1,'0131525239') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (2,'0131525239') ; INSERT INTO Titles (ISBN,Title,EditionNumber,Copyright) VALUES ('0132222205','Java How to Program',7,'2007') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (1,'0132222205') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (2,'0132222205') ; INSERT INTO Titles (ISBN,Title,EditionNumber,Copyright) VALUES ('0131857576','C++ How to Program',5,'2005') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (1,'0131857576') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (2,'0131857576') ; INSERT INTO Titles (ISBN,Title,EditionNumber,Copyright) VALUES ('0132404168','C How to Program',5,'2007') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (1,'0132404168') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (2,'0132404168') ; INSERT INTO Titles (ISBN,Title,EditionNumber,Copyright) VALUES ('0131450913','Internet & World Wide Web How to Program',3,'2004') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (1,'0131450913') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (2,'0131450913') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (3,'0131450913') ; INSERT INTO Titles (ISBN,Title,EditionNumber,Copyright) VALUES ('0131828274','Operating Systems',3,'2004') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (1,'0131828274') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (2,'0131828274') ; INSERT INTO AuthorISBN (AuthorID,ISBN) VALUES (4,'0131828274') ;

ch28solutions/SQLscripts/mysql/employees.sql

DROP DATABASE IF EXISTS employees; CREATE DATABASE employees; USE employees; DROP TABLE IF EXISTS salariedEmployees; DROP TABLE IF EXISTS commissionEmployees; DROP TABLE IF EXISTS basePlusCommissionEmployees; DROP TABLE IF EXISTS hourlyEmployees; DROP TABLE IF EXISTS employees; CREATE TABLE employees ( socialSecurityNumber varchar (30) NOT NULL, firstName varchar (30) NOT NULL, lastName varchar (30) NOT NULL, birthday date NOT NULL, employeeType varchar (30) NOT NULL, departmentName varchar (30) NOT NULL, PRIMARY KEY (socialSecurityNumber) ) ; CREATE TABLE salariedEmployees ( socialsecurityNumber varchar (30) NOT NULL, weeklySalary real NOT NULL, bonus real, INDEX (socialSecurityNumber), FOREIGN KEY (socialSecurityNumber) REFERENCES employees (socialSecurityNumber) ) ; CREATE TABLE commissionEmployees ( socialSecurityNumber varchar (30) NOT NULL, grossSales int NOT NULL, commissionRate real NOT NULL, bonus real, INDEX (socialSecurityNumber), FOREIGN KEY (socialSecurityNumber) REFERENCES employees (socialSecurityNumber) ) ; CREATE TABLE basePlusCommissionEmployees ( socialSecurityNumber varchar (30) NOT NULL, grossSales int NOT NULL, commissionRate real NOT NULL, baseSalary real NOT NULL, bonus real, INDEX (socialSecurityNumber), FOREIGN KEY (socialSecurityNumber) REFERENCES employees (socialSecurityNumber) ) ; CREATE TABLE hourlyEmployees ( socialSecurityNumber varchar (30) NOT NULL, hours int NOT NULL, wage real NOT NULL, bonus real, INDEX (socialSecurityNumber), FOREIGN KEY (socialSecurityNumber) REFERENCES employees (socialSecurityNumber) ) ; INSERT INTO employees VALUES ('111-11-1111', 'John', 'Smith', '1945-1-2', 'salariedEmployee', 'R&D'); INSERT INTO employees VALUES ('222-22-2222', 'Sue', 'Jones', '1961-2-3', 'commissionEmployee', 'SALES'); INSERT INTO employees VALUES ('333-33-3333', 'Bob', 'Lowis', '1958-10-5', 'basePlusCommissionEmployee', 'SALES'); INSERT INTO employees VALUES ('444-44-4444', 'Karen', 'Price', '1972-5-25', 'hourlyEmployee', 'HR'); INSERT INTO salariedEmployees VALUES ('111-11-1111', 2013.67, 0); INSERT INTO commissionEmployees VALUES ('222-22-2222', 10100, 0.05, 0); INSERT INTO basePlusCommissionEmployees VALUES ('333-33-3333', 5000, 0.04, 300, 0); INSERT INTO hourlyEmployees VALUES ('444-44-4444', 30, 35.5, 0);