[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 399
  • Last Modified:

Error-NullPointer

This is the error that I am getting when I run my program.  Can you tell me what the problem is for this program?

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
      at AddressBookDisplay$9.windowClosing(AddressBookDisplay.java:267)
      at java.awt.AWTEventMulticaster.windowClosing(AWTEventMulticaster.java:332)
      at java.awt.Window.processWindowEvent(Window.java:1865)
      at javax.swing.JFrame.processWindowEvent(JFrame.java:274)
      at java.awt.Window.processEvent(Window.java:1823)
      at java.awt.Component.dispatchEventImpl(Component.java:4651)
      at java.awt.Container.dispatchEventImpl(Container.java:2099)
      at java.awt.Window.dispatchEventImpl(Window.java:2478)
      at java.awt.Component.dispatchEvent(Component.java:4481)
      at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643)
      at java.awt.EventQueue.access$000(EventQueue.java:84)
      at java.awt.EventQueue$1.run(EventQueue.java:602)
      at java.awt.EventQueue$1.run(EventQueue.java:600)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
      at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
      at java.awt.EventQueue$2.run(EventQueue.java:616)
      at java.awt.EventQueue$2.run(EventQueue.java:614)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
      at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

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;
   private JButton deleteButton;
      
   // 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();
            deleteButton = new JButton();

           setLayout( new FlowLayout( FlowLayout.CENTER, 10, 10 ) );
      setSize( 400, 400 );
      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 Current Entry" );
            updateButton.addActionListener(
                  new ActionListener()
                  {
                        public void actionPerformed( ActionEvent evt )
                        {
                              updateButtonActionPerformed( evt );
                        } // end method actionPerformed
                  } // end anonymous inner class
                  );// end call to ActionListener
           
            add( updateButton );
                        
                  deleteButton.setText( "Delete Current Entry" );
            deleteButton.addActionListener(
                  new ActionListener()
                  {
                        public void actionPerformed( ActionEvent evt )
                        {
                              deleteButtonActionPerformed( evt );
                        } // end method actionPerformed
                  } // end anonymous inner class
                  );// end call to ActionListener
           
            add( deleteButton );                        
            
      addWindowListener(
         new WindowAdapter()
         {  
            public void windowClosing( WindowEvent evt )
            {
               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 indexTextField
   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
   
      private void updateButtonActionPerformed( ActionEvent evt )
      {
         int result = personQueries.updatePerson( firstNameTextField.getText(),
         lastNameTextField.getText(), emailTextField.getText(),
         phoneTextField.getText() );
            if ( result == 1 )
                  JOptionPane.showMessageDialog( this, "Person updated!",
                        "Person updated", JOptionPane.PLAIN_MESSAGE );
            else
                  JOptionPane.showMessageDialog( this, "Person not updated!",
                        "Person not updated", JOptionPane.PLAIN_MESSAGE );
                       
            updateButtonActionPerformed( evt );
      } // end method updateButtonActionPerformed
            
            private void   deleteButtonActionPerformed(ActionEvent evt )
      {
           int result = personQueries.deletePerson(Integer.parseInt(idTextField.getText()) );
     
      if ( result == 1 )
         JOptionPane.showMessageDialog( this, "Person Deleted!",
            "Person Data Updated!", JOptionPane.PLAIN_MESSAGE );
      else
         JOptionPane.showMessageDialog( this, "Person Data not Deleted!",
            "Error", JOptionPane.PLAIN_MESSAGE );
            browseButtonActionPerformed(evt);
      } // end method deleteButtonActionPerformed
   
      public static void main( String args[] )
   {
      new AddressBookDisplay();
   } // end method main
} //

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;
   private JButton deleteButton;
      
   // 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();
            deleteButton = new JButton();

           setLayout( new FlowLayout( FlowLayout.CENTER, 10, 10 ) );
      setSize( 400, 400 );
      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 Current Entry" );
            updateButton.addActionListener(
                  new ActionListener()
                  {
                        public void actionPerformed( ActionEvent evt )
                        {
                              updateButtonActionPerformed( evt );
                        } // end method actionPerformed
                  } // end anonymous inner class
                  );// end call to ActionListener
           
            add( updateButton );
                        
                  deleteButton.setText( "Delete Current Entry" );
            deleteButton.addActionListener(
                  new ActionListener()
                  {
                        public void actionPerformed( ActionEvent evt )
                        {
                              deleteButtonActionPerformed( evt );
                        } // end method actionPerformed
                  } // end anonymous inner class
                  );// end call to ActionListener
           
            add( deleteButton );                        
            
      addWindowListener(
         new WindowAdapter()
         {  
            public void windowClosing( WindowEvent evt )
            {
               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 indexTextField
   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
   
      private void updateButtonActionPerformed( ActionEvent evt )
      {
         int result = personQueries.updatePerson( firstNameTextField.getText(),
         lastNameTextField.getText(), emailTextField.getText(),
         phoneTextField.getText() );
            if ( result == 1 )
                  JOptionPane.showMessageDialog( this, "Person updated!",
                        "Person updated", JOptionPane.PLAIN_MESSAGE );
            else
                  JOptionPane.showMessageDialog( this, "Person not updated!",
                        "Person not updated", JOptionPane.PLAIN_MESSAGE );
                       
            updateButtonActionPerformed( evt );
      } // end method updateButtonActionPerformed
            
            private void   deleteButtonActionPerformed(ActionEvent evt )
      {
           int result = personQueries.deletePerson(Integer.parseInt(idTextField.getText()) );
     
      if ( result == 1 )
         JOptionPane.showMessageDialog( this, "Person Deleted!",
            "Person Data Updated!", JOptionPane.PLAIN_MESSAGE );
      else
         JOptionPane.showMessageDialog( this, "Person Data not Deleted!",
            "Error", JOptionPane.PLAIN_MESSAGE );
            browseButtonActionPerformed(evt);
      } // end method deleteButtonActionPerformed
   
      public static void main( String args[] )
   {
      new AddressBookDisplay();
   } // end method main
} //
import java.sql.*;
import java.util.List;
import java.util.ArrayList;

public class PersonQueries
{
   private static String URL = "jdbc:derby:AddressBook;create=true";

   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 updatePerson = null;
      private PreparedStatement deletePerson = null;
   // constructor
   public PersonQueries()
   {
     
            try
      {
               Class.forName("org.apache.derby.jdbc.EmbeddedDriver");      
                  
                  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 ( ?, ?, ?, ? )" );
                        
                  // create updates current entry in the database
                  updatePerson = connection.prepareStatement(
                      "UPDATE Addresses " +
                      "SET LastName = ?, " +
                      "FirstName = ?, " +
                    "PhoneNumber = ?, " +
                      "Email = ?, " +
                      "WHERE AddressID = ?");
                  
                  // delete the current entry in the database      
                  deletePerson = connection.prepareStatement(
                    "DELETE FROM Adresses " +
                    "WHERE ID = ?");      
                        } // end try
      catch ( Exception 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
      
      public int updatePerson(
                  String fname, String lname, String email, String num )
      {
            int result = 0;
                        
      try{
                      updatePerson.setString(1, fname );
            updatePerson.setString(2, lname );
            updatePerson.setString(3, email );
            updatePerson.setString(4, num );
                   
                        // update the current entry;
                        result = updatePerson.executeUpdate();
        } // end try
              catch (SQLException e)
                     {
            e.printStackTrace();
        } // end catch
            return result;
      } // end updatePerson
      
      public int deletePerson( int uid )
   {
      int result = 0;
     
      // set parameterss, then execute editNewPersons
      try
      {
         deletePerson.setInt( 1, uid );

         // modify the  entry; returns # of rows updated
         result = deletePerson.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 class PersonQueries




address.sql
derby.log
0
assaultkitty
Asked:
assaultkitty
  • 26
  • 17
22 Solutions
 
assaultkittyAuthor Commented:
It is a runtime error.
0
 
for_yanCommented:
when does such exception happen?
0
 
for_yanCommented:
you posted twice the code above - are those identical codes ?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
for_yanCommented:

You need to uncomment this line:
    personQueries = new PersonQueries();

It is commented oyut is your code, when you then try execute the method on personqueries istance which was not create - it cauases NullPointer
0
 
for_yanCommented:

It is right here :
    
   // no-argument constructor
   public AddressBookDisplay()
   {
      super( "Address Book" ); 
      
      // establish database connection and set up PreparedStatements
     // personQueries = new PersonQueries(); 
      
      // create GUI

Open in new window


you need to uncomment :
change

  // personQueries = new PersonQueries();

to

personQueries = new PersonQueries();




 
0
 
assaultkittyAuthor Commented:
No.  I made some changes.  It includes the deletePerson code, also.
0
 
for_yanCommented:
I know - I already pasted in your new code.

You still need to uncomment the line:

 // personQueries = new PersonQueries();


0
 
assaultkittyAuthor Commented:
Now, I think the reason we commented out // personQueries = new PersonQueries();  was because of this error at this line in PersonQueries

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

This is the compilation error.

java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver
      at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
      at java.lang.Class.forName0(Native Method)
      at java.lang.Class.forName(Class.java:169)
      at PersonQueries.<init>(PersonQueries.java:31)
      at AddressBookDisplay.<init>(AddressBookDisplay.java:67)
      at AddressBookDisplay.main(AddressBookDisplay.java:422)

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.
0
 
for_yanCommented:
well, we already went through that once
You need to put derby-10.5.3.0_1.jar in the classpath - did you download it yesterady ?
0
 
for_yanCommented:


http://mirrors.ibiblio.org/pub/mirrors/maven2/org/apache/derby/derby/10.5.3.0_1/derby-10.5.3.0_1.jar

This is how to add library to JGrasp project:

http://www.jgrasp.org/jgrasp/howto1.htm

How To Change the Classpath for Java Programs

Go to Settings > PATH/CLASSPATH > Workspace from the control panel.

Select the CLASSPATH tab in the settings dialog if not already selected, then hit the New button.

In the New CLASSPATH / Doc Path dialog, click the Browse button for Path or JAR File and navigate to the JAR file or the folder containing the target Java package root, and click Choose.

(Optional) If you would like set the documentation path for the classes in the JAR or package folder, click the Browse button for Documentation Path, select the folder containing the associated javadoc documentation, and click Choose.

Finally, click OK on the New CLASSPATH / Doc Path dialog, and OK on the settings dialog.

 
0
 
assaultkittyAuthor Commented:
I downloaded the jar file.  I put it in the

CLASSPATH .;C:\mysql-connector-java-5.1.18\mysql-connector-java-5.1.18-bin.jar;C:\derby-10.5.3.0_1.jar

Is this correct. Do I need to add something else?
0
 
for_yanCommented:
You need to make sure that you have this jar in the root of of your C: drive at C:\derby-10.5.3.0_1.jar
And this would be good if you do it on cmmmand line

If you are doing it in IDE - you should do browsing as it is methioned above - and they will create CLASSPATH
for you
0
 
assaultkittyAuthor Commented:
At the ij command line.  I get a message that says the AddressBook is not created.  How do I create this database with the bat files.
0
 
for_yanCommented:
Well, that measn that driver is no longer a problem.
I acually created just with create=true from within the code
but I guess if you want to create particular scheme you want to do it separatelty
0
 
assaultkittyAuthor Commented:
I am still getting the class not found error.  I make a connection to a database.  I do not know what could possibly be the problem.  Can you help?
 
0
 
for_yanCommented:
which class you are not finding?
How can there be class not found for the driver if you are connecting to database and it says that AddressBook is not ccreated - itmeans
it passed the point abourt driver; which class is not found?
0
 
for_yanCommented:


>At the ij command line


what is    ij command line ?
0
 
assaultkittyAuthor Commented:
These are the commands according to the book that I have to take to start the derby

cd C:\Progam Files\Sun\JavaDB\bin
setEmbeddedCP.bat
cd C:\Documents and Settings\Administrator\My Documents\AddressBook Modification-28.8_BP
"C:\Program Files\Sun\JavaDB\bin\ij"
connect 'jdbc:derby;AddressBook;create=true;user=deitel;password=deitel';
run address.sql;
exit;
0
 
assaultkittyAuthor Commented:
It is the same message as before.

java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver
      at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
      at java.lang.Class.forName0(Native Method)
      at java.lang.Class.forName(Class.java:169)
      at PersonQueries.<init>(PersonQueries.java:31)
      at AddressBookDisplay.<init>(AddressBookDisplay.java:67)
      at AddressBookDisplay.main(AddressBookDisplay.java:422)
0
 
for_yanCommented:
And what happens?

Actually, if you don't care about schema I yesterday created it right from the code like that:

 private static String URL = "jdbc:derby:AddressBook1;create=true";

 Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
         connection =
            DriverManager.getConnection( URL);
0
 
for_yanCommented:
when does this happen?

It is the same message as before.

java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver
      at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
      at java.lang.Class.forName0(Native Method)
      at java.lang.Class.forName(Class.java:169)
      at PersonQueries.<init>(PersonQueries.java:31)
      at AddressBookDisplay.<init>(AddressBookDisplay.java:67)
      at AddressBookDisplay.main(AddressBookDisplay.java:422)
0
 
for_yanCommented:
Do you see it when you run your appliaction, or when you run those

connect 'jdbc:derby;AddressBook;create=true;user=deitel;password=deitel';

etc. ?

I'd suggest to use default scheme - without this: user=deitel;password=deitel'; - then you don't need to do anything outside your code
0
 
assaultkittyAuthor Commented:
I see this message when I compile the AddressBookDisplay.java file.  I use the connect 'jdbc:derby;AddressBook;create=true;user=deitel;password=deitel'; at the command line when I set up the connection to the database.  
0
 
for_yanCommented:
YOu see that message not when you compile but when you start execting your application.
It cannot be at the compile time.
It is runtime error.

Forget about connect... and all this stuff  - you don;t need it - I'll show you.
You can do all of that from the code.

You need to cioncentrate on this message ClassNot Found when you run your address book.

Once again respond clearly - are you running AddressBookDisplay - from command line or from IDE (jGrasp)?



0
 
assaultkittyAuthor Commented:
I am running from the jGrasp.
0
 
for_yanCommented:
then go through this and make sure you put this derby-10....jar on the classpath:
---------------------------------
How To Change the Classpath for Java Programs

Go to Settings > PATH/CLASSPATH > Workspace from the control panel.

Select the CLASSPATH tab in the settings dialog if not already selected, then hit the New button.

In the New CLASSPATH / Doc Path dialog, click the Browse button for Path or JAR File and navigate to the JAR file or the folder containing the target Java package root, and click Choose.

(Optional) If you would like set the documentation path for the classes in the JAR or package folder, click the Browse button for Documentation Path, select the folder containing the associated javadoc documentation, and click Choose.

Finally, click OK on the New CLASSPATH / Doc Path dialog, and OK on the settings dialog.
------
let me know that you went thriough this part without problems

 


0
 
for_yanCommented:
Don't execute the program yet - jsut let me know that you went through that part
0
 
for_yanCommented:
don't do this part:
------------------------
(Optional) If you would like set the documentation path for the classes in the JAR or package folder, click the Browse button for Documentation Path, select the folder containing the associated javadoc documentation, and click Choose.
--------------------------
0
 
assaultkittyAuthor Commented:
I am working in a virtual environment on Windows XP.  Which setting are you talking about.  The system settings?
0
 
assaultkittyAuthor Commented:
This is the ClassPath for the .;C:\mysql-connector-java-5.1.18\mysql-connector-java-5.1.18-bin.jar;C:\derby-10.5.3.0_1.jar
0
 
for_yanCommented:

No this is all within jGrasp - not in your system it is inside your jgarsp IDE.
and control panel - they mean the one within jGrasp:

http://www.jgrasp.org/jgrasp/control.htm#ctrl_top

not the one of the entier system.


Go to Settings > PATH/CLASSPATH > Workspace from the control panel.

Select the CLASSPATH tab in the settings dialog if not already selected, then hit the New button.

In the New CLASSPATH / Doc Path dialog, click the Browse button for Path or JAR File and navigate to the JAR file or the folder containing the target Java package root, and click Choose.

Finally, click OK on the New CLASSPATH / Doc Path dialog, and OK on the settings dialog.




0
 
for_yanCommented:
Let's follow one thread - what is this:
>This is the ClassPath for the .;C:\mysql-connector-java-5.1.18\mysql-connector-java-5.1.18-bin.jar;C:\derby-10.5.3.0_1.jar


Please, go to jGrasp and execute those operations which I posted already n times.
If that is impossible or not undersatndable - please explain what is the problem.

Otherwise perform these operstions. You are doing weverything inside jGrasp - classpath for the project should be set up within jGrasp
0
 
assaultkittyAuthor Commented:
OK.
0
 
for_yanCommented:

And if you successfully perfomr this stuff with cvlasspath - do not try to execute your program, rather let me know that you set the classpath.
0
 
assaultkittyAuthor Commented:
Finished with JGrasp settings.  Did not execute yet.
0
 
for_yanCommented:

OK.
Asusuming that you never yet has passed beyond classnot forun before - now do the followuing.

Copy your own PersonQueries.java soehwrw to prserve it and replace the conetent of your
PersonQueries.java file within your project in JGrasp withthe following file
and try to execute program -it sould exit soon - it should only create a scheme for you this time.

Post waht you see.

import java.sql.*;
import java.util.List;
import java.util.ArrayList;

public class PersonQueries
{
   private static String URL = "jdbc:derby:AddressBook;create=true";

   //  private static String URL = "jdbc:derby:AddressBook2;user=deitel;password=deitel";

   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 updatePerson = null;
      private PreparedStatement deletePerson = null;
   // constructor
   public PersonQueries()
   {

            try
      {
               Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

                  connection = DriverManager.getConnection( URL );

         //   connection = DriverManager.getConnection( URL, USERNAME, PASSWORD );

              Statement stmt = connection.createStatement();
            stmt.executeUpdate ("create schema deitel authorization deitel");

          if(true) {connection.close();
                System.exit(0);
         }


       //  stmt.executeUpdate("create table addresses (AddressID int primary key GENERATED  ALWAYS AS IDENTITY , FirstName varchar(25), LastName varchar(25), Email varchar(25), PhoneNumber varchar(25))");

          

         // 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 ( ?, ?, ?, ? )" );

                  // create updates current entry in the database
                  updatePerson = connection.prepareStatement(
                      "UPDATE Addresses " +
                      "SET LastName = ?, " +
                      "FirstName = ?, " +
                    "PhoneNumber = ?, " +
                      "Email = ? " +
                      "WHERE AddressID = ?");

                  // delete the current entry in the database
                  deletePerson = connection.prepareStatement(
                    "DELETE FROM Addresses " +
                    "WHERE AddressID = ?");
                        } // end try
      catch ( Exception 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

      public int updatePerson(
                  String fname, String lname, String email, String num )
      {
            int result = 0;

      try{
                      updatePerson.setString(1, fname );
            updatePerson.setString(2, lname );
            updatePerson.setString(3, email );
            updatePerson.setString(4, num );

                        // update the current entry;
                        result = updatePerson.executeUpdate();
        } // end try
              catch (SQLException e)
                     {
            e.printStackTrace();
        } // end catch
            return result;
      } // end updatePerson

      public int deletePerson( int uid )
   {
      int result = 0;

      // set parameterss, then execute editNewPersons
      try
      {
         deletePerson.setInt( 1, uid );

         // modify the  entry; returns # of rows updated
         result = deletePerson.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 class PersonQueries

Open in new window

0
 
for_yanCommented:
ACtually in the positive outcome there would not be much to see -it will just start and exit.
In the negative case you should see an exception. Post that one.
0
 
assaultkittyAuthor Commented:

 ----jGRASP exec: java AddressBookDisplay


 ----jGRASP: operation complete.

I did not see the GUI.  But this is the output.
0
 
for_yanCommented:
great!

Now again replace the code of PersonQueries and try tp execute.
Let me know.

import java.sql.*;
import java.util.List;
import java.util.ArrayList;

public class PersonQueries
{
  // private static String URL = "jdbc:derby:AddressBook3;create=true";

     private static String URL = "jdbc:derby:AddressBook;user=deitel;password=deitel";

   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 updatePerson = null;
      private PreparedStatement deletePerson = null;
   // constructor
   public PersonQueries()
   {

            try
      {
               Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

                  connection = DriverManager.getConnection( URL );

         //   connection = DriverManager.getConnection( URL, USERNAME, PASSWORD );

              Statement stmt = connection.createStatement();
           // stmt.executeUpdate ("create schema deitel authorization deitel");

        //  if(true) {connection.close();
         //       System.exit(0);
        // }


         stmt.executeUpdate("create table addresses (AddressID int primary key GENERATED  ALWAYS AS IDENTITY , FirstName varchar(25), LastName varchar(25), Email varchar(25), PhoneNumber varchar(25))");

          

         // 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 ( ?, ?, ?, ? )" );

                  // create updates current entry in the database
                  updatePerson = connection.prepareStatement(
                      "UPDATE Addresses " +
                      "SET LastName = ?, " +
                      "FirstName = ?, " +
                    "PhoneNumber = ?, " +
                      "Email = ? " +
                      "WHERE AddressID = ?");

                  // delete the current entry in the database
                  deletePerson = connection.prepareStatement(
                    "DELETE FROM Addresses " +
                    "WHERE AddressID = ?");
                        } // end try
      catch ( Exception 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

      public int updatePerson(
                  String fname, String lname, String email, String num )
      {
            int result = 0;

      try{
                      updatePerson.setString(1, fname );
            updatePerson.setString(2, lname );
            updatePerson.setString(3, email );
            updatePerson.setString(4, num );

                        // update the current entry;
                        result = updatePerson.executeUpdate();
        } // end try
              catch (SQLException e)
                     {
            e.printStackTrace();
        } // end catch
            return result;
      } // end updatePerson

      public int deletePerson( int uid )
   {
      int result = 0;

      // set parameterss, then execute editNewPersons
      try
      {
         deletePerson.setInt( 1, uid );

         // modify the  entry; returns # of rows updated
         result = deletePerson.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 class PersonQueries

Open in new window

0
 
assaultkittyAuthor Commented:
I am sorry it did not finish executing this is the Exception errors.

 ----jGRASP exec: java AddressBookDisplay


 ----jGRASP: operation complete.

 ----jGRASP exec: java AddressBookDisplay

java.sql.SQLException: Schema 'DEITEL' already exists.
      at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
      at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
      at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
      at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
      at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
      at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
      at org.apache.derby.impl.jdbc.EmbedStatement.executeStatement(Unknown Source)
      at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
      at org.apache.derby.impl.jdbc.EmbedStatement.executeUpdate(Unknown Source)
      at PersonQueries.<init>(PersonQueries.java:35)
      at AddressBookDisplay.<init>(AddressBookDisplay.java:67)
      at AddressBookDisplay.main(AddressBookDisplay.java:422)
Caused by: java.sql.SQLException: Schema 'DEITEL' already exists.
      at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
      at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
      ... 12 more
Caused by: ERROR X0Y68: Schema 'DEITEL' already exists.
      at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
      at org.apache.derby.impl.sql.execute.CreateSchemaConstantAction.executeConstantActionMinion(Unknown Source)
      at org.apache.derby.impl.sql.execute.CreateSchemaConstantAction.executeConstantAction(Unknown Source)
      at org.apache.derby.impl.sql.execute.MiscResultSet.open(Unknown Source)
      at org.apache.derby.impl.sql.GenericPreparedStatement.executeStmt(Unknown Source)
      at org.apache.derby.impl.sql.GenericPreparedStatement.execute(Unknown Source)
      ... 6 more

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.
0
 
for_yanCommented:

OK, still try to replcae the code which I posted last and try to execute it
0
 
assaultkittyAuthor Commented:
Oh my God that was it.  I entered a person and it said the person was added,  So explain to me what I need to do and what just happened.
0
 
for_yanCommented:
what you need to do is to comment out this line in your PersonQuesries:

 stmt.executeUpdate("create table addresses (AddressID int primary key GENERATED  ALWAYS AS IDENTITY , FirstName varchar(25), LastName varchar(25), Email varchar(25), PhoneNumber varchar(25))");

becuase next time you start it will complaine that the table already exists.

Waht you did - is first time it was supposed to create databse and the schema

As it wrote error - probably you still once before executed it succesfully, or maybe
you inadvertently tried to run  it second time right now - so it reported that schema
already existed.

In the enxt variant of code I removed creation of schema (and exit from application after it)
and added creation of the table - after creation of the table
you don't need to exist - you amy start using the table

However next tome you don't want to attempt to craete the table again, so now you need to
comment out this line.

After that it should allow you to add, delete, etc.

There were also many misprintes in the SQL inside PersonQueroes, extra commas, incorrect "Adress" instead of "Address" - I hope
I corrected thoses things - still maybe on some options liek Update or delete it may complain
 

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 26
  • 17
Tackle projects and never again get stuck behind a technical roadblock.
Join Now