JAVA RUNTIME OBJECTS METHOD
7.3 PERFORM DATA MANIPULATIONS TO SQL SERVER DATABASE USING JAVA RUNTIME OBJECT
7.3.2 Perform Data Updating to SQL Server Database Using
Regularly, we do not need to update a faculty_id when we update a faculty record, since a better way to do that is to insert a new faculty record and delete the old one. The main reason for this is that a very complicated operation would be performed if the faculty_id were updated, since it is a primary key in the Faculty table and foreign keys in the
Course and the LogIn tables. To update a primary key, one needs to update foreign keys fi rst in the child tables and then update the primary key in the parent table. This will make our updating operation very complicated and easy to be confused. In order to avoid this confusion, in this section, we will update a faculty record by changing any column except the faculty_id , and this is a popular way to update a table and widely implemented in most database applications.
7.3.2.1 Develop the Codes for the Update Button Event Handler
We want to use the Update button we built in this FacultyFrame form window to perform the faculty updating function; therefore no any modifi cation to this FacultyFrame form window to be made. Now, let ’ s develop the codes for the Update button click event handler.
Open this event handler and enter the codes that are shown in Figure 7.27 into this event handler. Let ’ s have a closer look at this piece of codes to see how it works.
A. Two local variables, numUpdated and cFacultyName , are created fi rst, and these two variables are used to hold the running result of the data updating action and the current faculty name.
Figure 7.27. The developed codes for the Update button click event handler.
private void cmdUpdateActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
int numUpdated = 0;
String cFacultyName = null;
String query = "UPDATE Faculty SET faculty_name=?, title=?, office=?, phone=?, college=?, email=? " + "WHERE faculty_name= ?";
try {
PreparedStatement pstmt = LogInFrame.con.prepareStatement(query);
pstmt.setString(1, FacultyNameField.getText());
pstmt.setString(2, TitleField.getText());
pstmt.setString(3, OfficeField.getText());
pstmt.setString(4, PhoneField.getText());
pstmt.setString(5, CollegeField.getText());
pstmt.setString(6, EmailField.getText());
pstmt.setString(7, ComboName.getSelectedItem().toString());
cFacultyName = (String)ComboName.getSelectedItem();
numUpdated = pstmt.executeUpdate();
}
catch (SQLException e) {
msgDlg.setMessage("Error in Statement!" + e.getMessage());
msgDlg.setVisible(true);
}
System.out.println("The number of updated row = " + numUpdated);
ComboName.addItem(FacultyNameField.getText());
ComboName.removeItem(cFacultyName);
} A B
C D
E F G
H I J
B. The updating query string is created with six positional parameters. The query criterion is the faculty name that is placed after the WHERE clause.
C. A try … catch block is used to assist this data updating action. First, a PreparedStatement instance is created using the Connection object that is located at the LogInFrame class with the updating query string as the argument.
D. The setString() method is used to initialize six pieces of updated faculty information, which are obtained from six text fi elds and entered by the user as the project runs.
E. After this faculty record has been updated, we need to remove the current or old faculty name from the Faculty Name combo box and add the updated faculty name into that box.
In order to remember the current faculty name, we need to temporarily store it into our local string variable cFacultyName .
F. The data updating action is performed by calling the executeUpdate() method. The updat- ing result, which is an integer number that is equal to the number of rows that have been updated by this data updating action, is returned and assigned to the local integer variable numUpdated .
G. The catch block is used to track and collect any possible exception encountered when this data updating is executed.
H. The running result is printed out as a debug purpose.
I. The updated faculty name is added into the Faculty Name combo box to enable the users to validate this data updating later.
J. The current or old faculty name is removed from this Faculty Name combo box.
Now, let ’ s build and run the project to test the data updating action.
7.3.2.2 Build and Run the Project to Test the Data Updating Before you can run this project, the following conditions have to be met:
• The SQL Server sample database CSE_DEPT has been connected to this project. To check this connection, open the Services window and expand the Databases node to locate our sample database connection URL, jdbc:sqlserver://localhost\SQL2008EXPRESS:
5000;databaseName=CSE_DEPT [ybai on dbo] . Right click on this URL and select the Connect item to do this connection.
Click on the Clean and Build Main Project button from the toolbar to build our project. Then click on the Run Main Project button to run the project.
Enter a suitable username and password, such as jhenry and test , to complete the login process and select the Faculty Information from the SelectFrame window to open the FacultyFrame window. Make sure that the Runtime Object Method has been selected from the Query Method combo box. Then click on the Select button to query the default faculty information. The default faculty information is displayed.
Enter the following information into six Text Fields (no Faculty ID Text Field) inside the Faculty Information panel as an updated faculty record, as shown in Figure 7.28 .
1. Name: Susan Bai 2. Title: Professor 3. Offi ce: MTC - 215 4. Phone: 750 - 378 - 1111
c07.indd 497
c07.indd 497 7/20/2011 11:12:07 AM7/20/2011 11:12:07 AM
www.traintelco.com
5. College: Duke University 6. Email: sbai@college.com
Also, enter the name of a default faculty image fi le, Default.jpg , to the Faculty Image fi eld since we want to update this faculty ’ s image with this data updating. Your fi nished updating window should match one that is shown in Figure 7.28 .
Click on the Update button to perform this data updating. Immediately, you can fi nd that the updated faculty name Susan Bai has been added into the Faculty Name combo box and the original faculty member Ying Bai has been removed from this box when clicking on the drop - down arrow of that box.
To validate this data updating, open the Output window if it has not been opened.
You can fi nd that a running successful message is displayed in that window, as shown in Figure 7.29 .
Similar to the data insertion operation, here we have two ways to validate this data updating. One way is to open our Faculty table to confi rm this data updating, and the other way is to use the Select button (exactly the codes inside that button ’ s click event handler) to do this validation. We prefer to use the second way to do this validation. Click on the Select button to try to retrieve this updated faculty record, and the running result is shown in Figure 7.30 .
Our data updating action is successful!
Figure 7.28. The entered faculty updating information.
Figure 7.29. The successful data updating message.
It is highly recommended to recover that updated faculty record to keep our database clean and neat. Refer to Section 7.1.3.2 to do this recovery job. Of course, you can also perform this data recovering job using the codes in the Update button click event handler to do another data updating action again.
Next, let ’ s handle the data deletion action against our sample database.