Advanced Java 2 Platform HOW TO PROGRAM phần 4 potx

187 369 0
Advanced Java 2 Platform HOW TO PROGRAM phần 4 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 8 Java Database Connectivity (JDBC) 499 database and uses that information to set the parameters of PreparedStatements sqlUpdateName (lines 208–210), sqlUpdateAddress (lines 220–225), sqlUp- datePhone (lines 235–236) and sqlUpdateEmail (lines 246–247). Note that param- eter values are set by invoking PreparedStatement set methods for the appropriate data type. In this example, the ID parameters are all integers and the remaining data are all strings, so the program uses methods setInt and setString to specify parameters. After setting the parameters for a particular PreparedStatement, the method calls that statement’s executeUpdate method (lines 211, 226, 237 and 248), which returns an integer indicating the number of rows modified by the update. The execution of each Pre- paredStatement is followed by an if structure that tests the return value of exe- cuteUpdate. If executeUpdate returns 0, the PreparedStatement did not update any records. Therefore, savePerson invokes Connection method rollback to restore the database to its state before the PreparedStatement executed and returns false to indicate to the AddressBook application that the update failed. If save- Person reaches line 256, it commits the transaction in the database and returns true to indicate that the update was successful. CloudscapeDataAccess method newPerson (lines 278–367) is similar to method savePerson. Method newPerson receives an AddressBookEntry con- taining the complete information for a person to insert in the database and uses that infor- mation to set the parameters of PreparedStatements sqlInsertName (lines 286– 287), sqlInsertAddress (lines 303–313), sqlInsertPhone (lines 323–325) and sqlInsertEmail (lines 335–337). The primary difference between newPerson and savePerson is that the entry does not exist in the database yet. To insert rows in tables addresses, phoneNumbers and emailAddresses, the personID foreign-key field for each new record must correspond to the personID primary-key field in the names table. The new personID in table names is not known until the program inserts the new record in the table. So, after inserting a new record into table names, line 297 exe- cutes PreparedStatement sqlPersonID to obtain the personID number for the last new person added to table names. Line 300 places this value in the local variable personID. Then, the program inserts records in tables addresses, phoneNumbers and emailAddresses, using the new personID as the value of the foreign-key field in each table. As in method savePerson, if no records are inserted after a given Pre- paredStatement executes, method newPerson rolls back the transaction and returns false to indicate that the insertion failed. Otherwise, method newPerson commits the transaction and returns true to indicate that the insertion succeeded. CloudscapeDataAccess method deletePerson (lines 371–435) receives an AddressBookEntry containing the personID of the person to remove from the data- base and uses that ID as the parameter value for the PreparedStatements sqlDeleteName, sqlDeleteAddress, sqlDeletePhone and sqlDelete- Email. When each PreparedStatement executes, it deletes all records with the spec- ified personID in the appropriate table. If any part of the delete fails, method deletePerson rolls back the transaction and returns false to indicate that the deletion failed. Otherwise, method deletePerson commits the transaction and returns true to indicate that the deletion succeeded. In the future, if this program supports multiple addresses, phone numbers and e-mail addresses for each person, this deletePerson method will delete all the information for a particular entry properly. 500 Java Database Connectivity (JDBC) Chapter 8 CloudscapeDataAccess methods close (lines 438–463) and finalize (lines 467–470) close the PreparedStatements and database connection. Method finalize is provided in case an object of class CloudscapeDataAccess gets gar- bage collected and the client forgot to call close explicitly. Class AddressBookEntryFrame (Fig. 8.37) is a subclass of JInternalFrame that enables address-book application users to view or edit the details of an Address- BookEntry. The AddressBook application class (Fig. 8.38) creates a new Address- BookEntryFrame to display the results of a search for an entry and to enable the user to input information for a new entry. AddressBookEntryFrame maintains a reference to the currently displayed AddressBookEntry and provides set and get methods to specify an AddressBookEntry to display and to return the currently displayed AddressBookEntry, respectively. The class also has several private utility methods for setting up the GUI and accessing the individual JTextFields in the GUI. Objects of class AddressBookEntryFrame are managed by class AddressBook, which con- tains a JDesktopPane. 1 // Fig. 8.37: AddressBookEntryFrame.java 2 // A subclass of JInternalFrame customized to display and 3 // an AddressBookEntry or set an AddressBookEntry's properties 4 // based on the current data in the UI. 5 package com.deitel.advjhtp1.jdbc.addressbook; 6 7 // Java core packages 8 import java.util.*; 9 import java.awt.*; 10 11 // Java extension packages 12 import javax.swing.*; 13 14 public class AddressBookEntryFrame extends JInternalFrame { 15 16 // HashMap to store JTextField references for quick access 17 private HashMap fields; 18 19 // current AddressBookEntry set by AddressBook application 20 private AddressBookEntry person; 21 22 // panels to organize GUI 23 private JPanel leftPanel, rightPanel; 24 25 // static integers used to determine new window positions 26 // for cascading windows 27 private static int xOffset = 0, yOffset = 0; 28 29 // static Strings that represent name of each text field. 30 // These are placed on JLabels and used as keys in 31 // HashMap fields. 32 private static final String FIRST_NAME = "First Name", Fig. 8.37 Fig. 8.37Fig. 8.37 Fig. 8.37 AddressBookEntryFrame for viewing and editing an AddressBookEntry (part 1 of 3). Chapter 8 Java Database Connectivity (JDBC) 501 33 LAST_NAME = "Last Name", ADDRESS1 = "Address 1", 34 ADDRESS2 = "Address 2", CITY = "City", STATE = "State", 35 ZIPCODE = "Zipcode", PHONE = "Phone", EMAIL = "Email"; 36 37 // construct GUI 38 public AddressBookEntryFrame() 39 { 40 super( "Address Book Entry", true, true ); 41 42 fields = new HashMap(); 43 44 leftPanel = new JPanel(); 45 leftPanel.setLayout( new GridLayout( 9, 1, 0, 5 ) ); 46 rightPanel = new JPanel(); 47 rightPanel.setLayout( new GridLayout( 9, 1, 0, 5 ) ); 48 49 createRow( FIRST_NAME ); 50 createRow( LAST_NAME ); 51 createRow( ADDRESS1 ); 52 createRow( ADDRESS2 ); 53 createRow( CITY ); 54 createRow( STATE ); 55 createRow( ZIPCODE ); 56 createRow( PHONE ); 57 createRow( EMAIL ); 58 59 Container container = getContentPane(); 60 container.add( leftPanel, BorderLayout.WEST ); 61 container.add( rightPanel, BorderLayout.CENTER ); 62 63 setBounds( xOffset, yOffset, 300, 300 ); 64 xOffset = ( xOffset + 30 ) % 300; 65 yOffset = ( yOffset + 30 ) % 300; 66 } 67 68 // set AddressBookEntry then use its properties to 69 // place data in each JTextField 70 public void setAddressBookEntry( AddressBookEntry entry ) 71 { 72 person = entry; 73 74 setField( FIRST_NAME, person.getFirstName() ); 75 setField( LAST_NAME, person.getLastName() ); 76 setField( ADDRESS1, person.getAddress1() ); 77 setField( ADDRESS2, person.getAddress2() ); 78 setField( CITY, person.getCity() ); 79 setField( STATE, person.getState() ); 80 setField( ZIPCODE, person.getZipcode() ); 81 setField( PHONE, person.getPhoneNumber() ); 82 setField( EMAIL, person.getEmailAddress() ); 83 } 84 Fig. 8.37 Fig. 8.37Fig. 8.37 Fig. 8.37 AddressBookEntryFrame for viewing and editing an AddressBookEntry (part 2 of 3). 502 Java Database Connectivity (JDBC) Chapter 8 85 // store AddressBookEntry data from GUI and return 86 // AddressBookEntry 87 public AddressBookEntry getAddressBookEntry() 88 { 89 person.setFirstName( getField( FIRST_NAME ) ); 90 person.setLastName( getField( LAST_NAME ) ); 91 person.setAddress1( getField( ADDRESS1 ) ); 92 person.setAddress2( getField( ADDRESS2 ) ); 93 person.setCity( getField( CITY ) ); 94 person.setState( getField( STATE ) ); 95 person.setZipcode( getField( ZIPCODE ) ); 96 person.setPhoneNumber( getField( PHONE ) ); 97 person.setEmailAddress( getField( EMAIL ) ); 98 99 return person; 100 } 101 102 // set text in JTextField by specifying field's 103 // name and value 104 private void setField( String fieldName, String value ) 105 { 106 JTextField field = 107 ( JTextField ) fields.get( fieldName ); 108 109 field.setText( value ); 110 } 111 112 // get text in JTextField by specifying field's name 113 private String getField( String fieldName ) 114 { 115 JTextField field = 116 ( JTextField ) fields.get( fieldName ); 117 118 return field.getText(); 119 } 120 121 // utility method used by constructor to create one row in 122 // GUI containing JLabel and JTextField 123 private void createRow( String name ) 124 { 125 JLabel label = new JLabel( name, SwingConstants.RIGHT ); 126 label.setBorder( 127 BorderFactory.createEmptyBorder( 5, 5, 5, 5 ) ); 128 leftPanel.add( label ); 129 130 JTextField field = new JTextField( 30 ); 131 rightPanel.add( field ); 132 133 fields.put( name, field ); 134 } 135 } // end class AddressBookEntryFrame Fig. 8.37 Fig. 8.37Fig. 8.37 Fig. 8.37 AddressBookEntryFrame for viewing and editing an AddressBookEntry (part 3 of 3). Chapter 8 Java Database Connectivity (JDBC) 503 Class AddressBook (Fig. 8.38) is the main application class for the address-book application. AddressBook uses several of the GUI techniques presented in Chapter 2, including tool bars, menus, actions and multiple-document interfaces. The discussion of class AddressBook concentrates on the functionality, rather than on the GUI details. Screen captures demonstrating the program’s execution appear in Fig. 8.39. 1 // Fig. 8.38: AddressBook.java 2 // An address book database example that allows information to 3 // be inserted, updated and deleted. The example uses 4 // transactions to ensure that the operations complete 5 // successfully. 6 package com.deitel.advjhtp1.jdbc.addressbook; 7 8 // Java core packages 9 import java.awt.*; 10 import java.awt.event.*; 11 import java.sql.*; 12 13 // Java extension packages 14 import javax.swing.*; 15 import javax.swing.event.*; 16 17 public class AddressBook extends JFrame { 18 19 // reference for manipulating multiple document interface 20 private JDesktopPane desktop; 21 22 // reference to database access object 23 private AddressBookDataAccess database; 24 25 // references to Actions 26 Action newAction, saveAction, deleteAction, 27 searchAction, exitAction; 28 29 // set up database connection and GUI 30 public AddressBook() 31 { 32 super( "Address Book" ); 33 34 // create database connection 35 try { 36 database = new CloudscapeDataAccess(); 37 } 38 39 // detect problems with database connection 40 catch ( Exception exception ) { 41 exception.printStackTrace(); 42 System.exit( 1 ); 43 } 44 Fig. 8.38 Fig. 8.38Fig. 8.38 Fig. 8.38 AddressBook application class that enables the user to interact with the addressbook database (part 1 of 8). 504 Java Database Connectivity (JDBC) Chapter 8 45 // database connection successful, create GUI 46 JToolBar toolBar = new JToolBar(); 47 JMenu fileMenu = new JMenu( "File" ); 48 fileMenu.setMnemonic( 'F' ); 49 50 // Set up actions for common operations. Private inner 51 // classes encapsulate the processing of each action. 52 newAction = new NewAction(); 53 saveAction = new SaveAction(); 54 saveAction.setEnabled( false ); // disabled by default 55 deleteAction = new DeleteAction(); 56 deleteAction.setEnabled( false ); // disabled by default 57 searchAction = new SearchAction(); 58 exitAction = new ExitAction(); 59 60 // add actions to tool bar 61 toolBar.add( newAction ); 62 toolBar.add( saveAction ); 63 toolBar.add( deleteAction ); 64 toolBar.add( new JToolBar.Separator() ); 65 toolBar.add( searchAction ); 66 67 // add actions to File menu 68 fileMenu.add( newAction ); 69 fileMenu.add( saveAction ); 70 fileMenu.add( deleteAction ); 71 fileMenu.addSeparator(); 72 fileMenu.add( searchAction ); 73 fileMenu.addSeparator(); 74 fileMenu.add( exitAction ); 75 76 // set up menu bar 77 JMenuBar menuBar = new JMenuBar(); 78 menuBar.add( fileMenu ); 79 setJMenuBar( menuBar ); 80 81 // set up desktop 82 desktop = new JDesktopPane(); 83 84 // get the content pane to set up GUI 85 Container c = getContentPane(); 86 c.add( toolBar, BorderLayout.NORTH ); 87 c.add( desktop, BorderLayout.CENTER ); 88 89 // register for windowClosing event in case user 90 // does not select Exit from File menu to terminate 91 // application 92 addWindowListener( 93 new WindowAdapter() { 94 public void windowClosing( WindowEvent event ) 95 { 96 shutDown(); Fig. 8.38 Fig. 8.38Fig. 8.38 Fig. 8.38 AddressBook application class that enables the user to interact with the addressbook database (part 2 of 8). Chapter 8 Java Database Connectivity (JDBC) 505 97 } 98 } 99 ); 100 101 // set window size and display window 102 Toolkit toolkit = getToolkit(); 103 Dimension dimension = toolkit.getScreenSize(); 104 105 // center window on screen 106 setBounds( 100, 100, dimension.width - 200, 107 dimension.height - 200 ); 108 109 setVisible( true ); 110 } // end AddressBook constructor 111 112 // close database connection and terminate program 113 private void shutDown() 114 { 115 database.close(); // close database connection 116 System.exit( 0 ); // terminate program 117 } 118 119 // create a new AddressBookEntryFrame and register listener 120 private AddressBookEntryFrame createAddressBookEntryFrame() 121 { 122 AddressBookEntryFrame frame = new AddressBookEntryFrame(); 123 setDefaultCloseOperation( DISPOSE_ON_CLOSE ); 124 frame.addInternalFrameListener( 125 new InternalFrameAdapter() { 126 127 // internal frame becomes active frame on desktop 128 public void internalFrameActivated( 129 InternalFrameEvent event ) 130 { 131 saveAction.setEnabled( true ); 132 deleteAction.setEnabled( true ); 133 } 134 135 // internal frame becomes inactive frame on desktop 136 public void internalFrameDeactivated( 137 InternalFrameEvent event ) 138 { 139 saveAction.setEnabled( false ); 140 deleteAction.setEnabled( false ); 141 } 142 } // end InternalFrameAdapter anonymous inner class 143 ); // end call to addInternalFrameListener 144 145 return frame; 146 } // end method createAddressBookEntryFrame 147 Fig. 8.38 Fig. 8.38Fig. 8.38 Fig. 8.38 AddressBook application class that enables the user to interact with the addressbook database (part 3 of 8). 506 Java Database Connectivity (JDBC) Chapter 8 148 // method to launch program execution 149 public static void main( String args[] ) 150 { 151 new AddressBook(); 152 } 153 154 // Private inner class defines action that enables 155 // user to input new entry. User must "Save" entry 156 // after inputting data. 157 private class NewAction extends AbstractAction { 158 159 // set up action's name, icon, descriptions and mnemonic 160 public NewAction() 161 { 162 putValue( NAME, "New" ); 163 putValue( SMALL_ICON, new ImageIcon( 164 getClass().getResource( "images/New24.png" ) ) ); 165 putValue( SHORT_DESCRIPTION, "New" ); 166 putValue( LONG_DESCRIPTION, 167 "Add a new address book entry" ); 168 putValue( MNEMONIC_KEY, new Integer( 'N' ) ); 169 } 170 171 // display window in which user can input entry 172 public void actionPerformed( ActionEvent e ) 173 { 174 // create new internal window 175 AddressBookEntryFrame entryFrame = 176 createAddressBookEntryFrame(); 177 178 // set new AddressBookEntry in window 179 entryFrame.setAddressBookEntry( 180 new AddressBookEntry() ); 181 182 // display window 183 desktop.add( entryFrame ); 184 entryFrame.setVisible( true ); 185 } 186 187 } // end inner class NewAction 188 189 // inner class defines an action that can save new or 190 // updated entry 191 private class SaveAction extends AbstractAction { 192 193 // set up action's name, icon, descriptions and mnemonic 194 public SaveAction() 195 { 196 putValue( NAME, "Save" ); 197 putValue( SMALL_ICON, new ImageIcon( 198 getClass().getResource( "images/Save24.png" ) ) ); 199 putValue( SHORT_DESCRIPTION, "Save" ); Fig. 8.38 Fig. 8.38Fig. 8.38 Fig. 8.38 AddressBook application class that enables the user to interact with the addressbook database (part 4 of 8). Chapter 8 Java Database Connectivity (JDBC) 507 200 putValue( LONG_DESCRIPTION, 201 "Save an address book entry" ); 202 putValue( MNEMONIC_KEY, new Integer( 'S' ) ); 203 } 204 205 // save new entry or update existing entry 206 public void actionPerformed( ActionEvent e ) 207 { 208 // get currently active window 209 AddressBookEntryFrame currentFrame = 210 ( AddressBookEntryFrame ) desktop.getSelectedFrame(); 211 212 // obtain AddressBookEntry from window 213 AddressBookEntry person = 214 currentFrame.getAddressBookEntry(); 215 216 // insert person in address book 217 try { 218 219 // Get personID. If 0, this is a new entry; 220 // otherwise an update must be performed. 221 int personID = person.getPersonID(); 222 223 // determine string for message dialogs 224 String operation = 225 ( personID == 0 ) ? "Insertion" : "Update"; 226 227 // insert or update entry 228 if ( personID == 0 ) 229 database.newPerson( person ); 230 else 231 database.savePerson( person ); 232 233 // display success or failure message 234 JOptionPane.showMessageDialog( desktop, 235 operation + " successful" ); 236 } // end try 237 238 // detect database errors 239 catch ( DataAccessException exception ) { 240 JOptionPane.showMessageDialog( desktop, exception, 241 "DataAccessException", 242 JOptionPane.ERROR_MESSAGE ); 243 exception.printStackTrace(); 244 } 245 246 // close current window and dispose of resources 247 currentFrame.dispose(); 248 249 } // end method actionPerformed 250 251 } // end inner class SaveAction Fig. 8.38 Fig. 8.38Fig. 8.38 Fig. 8.38 AddressBook application class that enables the user to interact with the addressbook database (part 5 of 8). 508 Java Database Connectivity (JDBC) Chapter 8 252 253 // inner class defines action that deletes entry 254 private class DeleteAction extends AbstractAction { 255 256 // set up action's name, icon, descriptions and mnemonic 257 public DeleteAction() 258 { 259 putValue( NAME, "Delete" ); 260 putValue( SMALL_ICON, new ImageIcon( 261 getClass().getResource( "images/Delete24.png" ) ) ); 262 putValue( SHORT_DESCRIPTION, "Delete" ); 263 putValue( LONG_DESCRIPTION, 264 "Delete an address book entry" ); 265 putValue( MNEMONIC_KEY, new Integer( 'D' ) ); 266 } 267 268 // delete entry 269 public void actionPerformed( ActionEvent e ) 270 { 271 // get currently active window 272 AddressBookEntryFrame currentFrame = 273 ( AddressBookEntryFrame ) desktop.getSelectedFrame(); 274 275 // get AddressBookEntry from window 276 AddressBookEntry person = 277 currentFrame.getAddressBookEntry(); 278 279 // If personID is 0, this is new entry that has not 280 // been inserted. Therefore, delete is not necessary. 281 // Display message and return. 282 if ( person.getPersonID() == 0 ) { 283 JOptionPane.showMessageDialog( desktop, 284 "New entries must be saved before they can be " + 285 "deleted. \nTo cancel a new entry, simply " + 286 "close the window containing the entry" ); 287 return; 288 } 289 290 // delete person 291 try { 292 database.deletePerson( person ); 293 294 // display message indicating success 295 JOptionPane.showMessageDialog( desktop, 296 "Deletion successful" ); 297 } 298 299 // detect problems deleting person 300 catch ( DataAccessException exception ) { 301 JOptionPane.showMessageDialog( desktop, exception, 302 "Deletion failed", JOptionPane.ERROR_MESSAGE ); Fig. 8.38 Fig. 8.38Fig. 8.38 Fig. 8.38 AddressBook application class that enables the user to interact with the addressbook database (part 6 of 8). [...]...Chapter 8 303 3 04 305 306 307 308 309 310 311 3 12 313 3 14 315 316 317 318 319 320 321 322 323 3 24 325 326 327 328 329 330 331 3 32 333 3 34 335 336 337 338 339 340 341 3 42 343 344 345 346 347 348 349 350 351 3 52 353 3 54 Fig 8.38 Java Database Connectivity (JDBC) 509 exception.printStackTrace(); } // close current window and... Practices for JDBC Programming.” Java Developers Journal, 5: no 4 (20 00): 42 54 Blaha, M R., W J Premerlani and J E Rumbaugh “Relational Database Design Using an ObjectOriented Methodology.” Communications of the ACM, 31: no 4 (1988): 41 4– 42 7 Brunner, R J “The Evolution of Connecting.” Java Developers Journal, 5: no 10 (20 00): 24 26 Chapter 8 Java Database Connectivity (JDBC) 529 Brunner, R J “After... index.html> . JOptionPane.ERROR_MESSAGE ); 24 3 exception.printStackTrace(); 24 4 } 24 5 24 6 // close current window and dispose of resources 24 7 currentFrame.dispose(); 24 8 24 9 } // end method actionPerformed 25 0 25 1 } // end. dialogs 22 4 String operation = 22 5 ( personID == 0 ) ? "Insertion" : "Update"; 22 6 22 7 // insert or update entry 22 8 if ( personID == 0 ) 22 9 database.newPerson( person ); 23 0. document interface 20 private JDesktopPane desktop; 21 22 // reference to database access object 23 private AddressBookDataAccess database; 24 25 // references to Actions 26 Action newAction,

Ngày đăng: 09/08/2014, 12:22

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan