Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
788
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

496 Chapter 7 Insert, Update, and Delete Data from Databases

7.3.2 Perform Data Updating to SQL Server Database Using Java Runtime Object

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 first 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 modification 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 first, and these two variables are used to hold the running result of the data updating action and the current faculty name.

private void cmdUpdateActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:

Aint numUpdated = 0; String cFacultyName = null;

BString query = "UPDATE Faculty SET faculty_name=?, title=?, office=?, phone=?, college=?, email=? " +

"WHERE faculty_name= ?";

try {

CPreparedStatement pstmt = LogInFrame.con.prepareStatement(query);

Dpstmt.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());

EcFacultyName = (String)ComboName.getSelectedItem();

FnumUpdated = pstmt.executeUpdate();

}

G catch (SQLException e) {

msgDlg.setMessage("Error in Statement!" + e.getMessage()); msgDlg.setVisible(true);

}

HSystem.out.println("The number of updated row = " + numUpdated);

IComboName.addItem(FacultyNameField.getText());

JComboName.removeItem(cFacultyName);

}

Figure 7.27. The developed codes for the Update button click event handler.

7.3 Perform Data Manipulations to SQL Server Database Using Java Runtime Object 497

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.Atry…catchblockisusedtoassistthisdataupdatingaction.First,aPreparedStatement 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 fields 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 updating 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.Office: MTC-215

4.Phone: 750-378-1111

498 Chapter 7 Insert, Update, and Delete Data from Databases

Figure 7.28. The entered faculty updating information.

Figure 7.29. The successful data updating message.

5.College: Duke University

6.Email: sbai@college.com

Also, enter the name of a default faculty image file, Default.jpg, to the Faculty

Image field since we want to update this faculty’s image with this data updating. Your

finished 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 find 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 find 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 confirm 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!

7.3 Perform Data Manipulations to SQL Server Database Using Java Runtime Object 499

Figure 7.30. The data updated result.

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.

7.3.3 Perform Data Deleting to SQL Server Database Using Java Runtime Object

Basically, there is no significant difference between the data updating and deleting using Java runtime object method. In this section, we try to use the Delete button we built in the FacultyFrame form window to perform this data deletion operation.

To make this deleting simple, we want to just delete the selected faculty record without touching the associated faculty image.

7.3.3.1 Develop the Codes for the Delete Button Event Handler

Open the Delete button click event handler and enter the codes that are shown in Figure 7.31 into this event handler. Let’s have a closer look at this piece of codes to see how it works.

A.Two local variables, numDeleted and cFacultyName, are created first, and these two variables are used to hold the running result of the data deleting action and the current faculty name.

B.The deleting query string is created with one positional parameter. 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 deleting action.First,a PreparedStatement instance is created using the Connection object that is located at the LogInFrame class with the deleting query string as the argument.

500 Chapter 7 Insert, Update, and Delete Data from Databases

private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) {

Aint numDeleted = 0;

String cFacultyName = null;

BString query = "DELETE FROM Faculty WHERE faculty_name = ?"; try {

CPreparedStatement pstmt = LogInFrame.con.prepareStatement(query);

Dpstmt.setString(1, ComboName.getSelectedItem().toString());

EcFacultyName = (String)ComboName.getSelectedItem();

FnumDeleted = pstmt.executeUpdate();

}

G catch (SQLException e) {

msgDlg.setMessage("Error in Statement!" + e.getMessage()); msgDlg.setVisible(true);

}

HSystem.out.println("The number of deleted row = " + numDeleted);

IComboName.removeItem(cFacultyName);

}

Figure 7.31. The developed codes for the Delete button click event handler.

D.The setString() method is used to initialize the positional parameter, which is the faculty name to be deleted from the Faculty Name combo box.

E.After this faculty record has been deleted, we need to remove this faculty name from the Faculty Name combo box. In order to remember the current faculty name, we need to temporarily store it into our local string variable cFacultyName.

F.The data deleting action is performed by calling the executeUpdate() method. The deleting result, which is an integer number that is equal to the number of rows that have been deleted by this data deleting action, is returned and assigned to the local integer variable numDeleted.

G.The catch block is used to track and collect any possible exception encountered when this data deleting is executed.

H.The running result is printed out as a debug purpose.

I.The deleted faculty name is removed from this Faculty Name combo box.

Now we are ready to build and run the project to test the data deletion function.

7.3.3.2 Build and Run the Project to Test the Data Deleting

Make sure that our sample database CSE_DEPT has been connected to our 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.

Now 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 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

7.3 Perform Data Manipulations to SQL Server Database Using Java Runtime Object 501

Figure 7.32. The successful data deletion message.

Table 7.8. The deleted faculty record in the faculty table

faculty_id

faculty_name

office

phone

college

title

email

B78880

Ying Bai

MTC-211

750-378-1148

Florida Atlantic University

Associate Professor

ybai@college.edu

from the Query Method combo box.Then click on the Select button to query the default faculty information. The default faculty information is displayed.

To test this data deletion function, we can try to delete one faculty member, such as Ying Bai, from our Faculty table. To do that, select this faculty member from the Faculty Name combo box, and click on the Delete button. Immediately, you can find that this faculty name has been removed from the Faculty Name combo box. Also, the running result is shown in the Output window, as shown in Figure 7.32.

To confirm this data deletion, click on the Back and the Exit button to stop our project. Then open our Faculty table by going to the Services window and expand the

Databases node, and our connection URL, and finally our sample database CSE_DEPT. Expand our database schema dbo and right click on the Faculty table. Select the View Data item from the pop-up menu to open our Faculty table. On the opened Faculty table, you can find that the faculty member Ying Bai has been removed from this table.

Our data deletion function is successful!

To make our database clean and neat, it is highly recommended to recover this deleted faculty member and related records in our Faculty, LogIn, Course, and StudentCourse tables. Refer to Tables 7.2–7.5 in Section 7.1.3.2 to complete these data recoveries. An easy way to do this is to use the Microsoft SQL Server 2008 Management Studio. For your convenience, we will show these deleted records in Tables 7.8–7.11 again, and you can add or insert them back to the related tables to complete this data recovery.

As we discussed in Section 6.4.2.3 in Chapter 6, in addition to using the executeUpdate() method to perform data manipulations, such as data insertion, updating, and deleting actions, one can use the execute() method to perform the similar data manipulations. I prefer to leave this optional method as a homework and allow students to handle this issue.

A complete sample project SQLSelectObject that can be used to perform data insertion, updating and deletion actions against our SQL Server sample database can be found from the folder DBProjects\Chapter 7 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).

502 Chapter 7 Insert, Update, and Delete Data from Databases

Table 7.9. The deleted course records in the course table

course_id

course

credit

classroom

schedule

enrollment

faculty_id

CSC-132B

Introduction to Programming

3

TC-302

T-H: 1:00-2:25 PM

21

B78880

CSC-234A

Data Structure & Algorithms

3

TC-302

M-W-F: 9:00-9:55 AM

25

B78880

CSE-434

Advanced Electronics Systems

3

TC-213

M-W-F: 1:00-1:55 PM

26

B78880

CSE-438

Advd Logic & Microprocessor

3

TC-213

M-W-F: 11:00-11:55 AM

35

B78880

Table 7.10. The deleted login records in the login table

user_name

pass_word

faculty_id

student_id

ybai

reback

B78880

NULL

 

 

 

 

Table 7.11. The deleted records in the studentcourse table

s_course_id

student_id

course_id

 

credit

major

1005

J77896

CSC-234A

3

CS/IS

1009

A78835

CSE-434

 

3

CE

1014

A78835

CSE-438

 

3

CE

1016

A97850

CSC-132B

 

3

ISE

1017

A97850

CSC-234A

 

3

ISE

Next, let’s take care of the data manipulations against the Oracle database using the Java runtime object method.

7.4 PERFORM DATA MANIPULATIONS TO ORACLE DATABASE USING JAVA RUNTIME OBJECT

Basically, there is no significant difference between a Java database application to access a SQL Server or an Oracle database. Because of the similarity in the coding process for both database applications, we only discuss those differences and highlight those parts in this section.

The following differences are existed between these two database applications:

1.The JDBC Driver

2.The JDBC API package used for the Oracle database interfaces

3.The JDBC database connection URL

4.The protocol and cursor used in the CallableStatements method

5.The protocol used in the RowSet method

7.4 Perform Data Manipulations to Oracle Database Using Java Runtime Object 503

The top three differences have been discussed in detailed in Sections 6.5.2.1–6.5.2.3, and the last two differences have also been discussed in Sections 6.5.4–6.5.6 in Chapter 6. To make this data manipulation simple, in this section, we only concentrate on the data manipulations to the Faculty table using the FacultyFrame class we built in Section 6.5.1 in Chapter 6.

To save time and space, we can use and modify a project OracleSelectObject we built in Chapter 6 to perform data manipulations against our target database. Perform the following operations to complete this project transferring:

1.Open the Windows Explorer and create a new folder, such as JavaDBProject\Chapter 7.

2.Open a Web browser and go to the folder DBProjects\Chapter 6 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).

3.Copy the project OracleSelectObject from that folder and paste it to our new folder

JavaDBProject\Chapter 7.

Now we are ready to build our data insertion query to perform data manipulations to our Oracle sample database CSE_DEPT.

7.4.1 Perform Data Insertion to Oracle Database Using Java Runtime Object

In Section 6.5.1 in Chapter 6, we have created a FacultyFrame class and Faculty JFrame window FacultyFrame. Also, the following components have been added into that project:

A JDBC driver for Oracle database has been loaded and registered.

A valid database connection to that project has been established.

A PreparedStatement instance has been created and implemented in the Select button click event handler to perform the data query.

In this section, we want to use the Insert button that has been added into the FacultyFrame window to perform this data insertion function. First, let’s do some modi-

fications to this FacultyFrame form window to enable us to perform the data manipulations.

7.4.1.1 Modify the FacultyFrame Window Form

First, let’s modify the FacultyFrame form by adding three more Text Fields into this frame: two of them are added into the Faculty Information panel to enable us to insert a faculty record, and one of them is added at the top of the faculty image box to allow us to insert a new faculty image (exactly the location of the faculty image).

Perform the following operations to open our pasted project OracleSelectObject:

1.Launch the NetBeans IDE 6.8 and go to File > Open Project menu item to open the Open Project wizard.

2.Browse to the location where we copied and pasted our project OracleSelectObject, which is JavaDBProject\Chapter 7. Make sure that the Open as Main Project checkbox has

been checked, and select this project and click on the Open Project button to open it.

504 Chapter 7

Insert, Update, and Delete Data from Databases

 

Table 7.12. Objects and controls added into the faculty frame window

 

 

 

 

 

 

 

Type

Variable Name

Text

editable

 

Title

Label

Label1

Faculty ID

 

 

 

Text Field

FacultyIDField

 

checked

 

 

Label

Label2

Name

 

 

 

Text Field

FacultyNameField

 

checked

 

 

Label

Label3

Faculty Image

 

 

 

Text Field

FacultyImageField

 

checked

 

 

The point to be noted is that you now have two OracleSelectObject projects in the NetBeans IDE, but they are different projects with different functions. The first OracleSelectObject was built in Chapter 6 without data manipulation function, but this second project will be built in Chapter 7 with the data manipulation function.

3.Expand this project files to open the FacultyFrame.java file by double clicking on this file that is located under the Source Packages\OracleSelectObject node.

4.Click on the Design button at the top of this window to open the GUI window of this FacultyFrame class.

Perform the following operations to add three more Text Fields into this frame window:

• Enlarge the FacultyFrame window form and the Faculty Information panel.

• Add two more labels and two more Text fields into this Faculty Information panel and one more label and the associated Text Field to the top of the Faculty Image box with the properties shown in Table 7.12.

One point to be noted is the FacultyIDField, and its editable property is checked, which means that we need to modify the faculty_id as the project runs since we may insert a new faculty record, including a new faculty_id, as the project runs. However, this field should be disabled when a data updating is performed, because we will not update it during a faculty record updating process. Your finished modified FacultyFrame form window should match one that is shown in Figure 7.33.

Now let’s develop the codes for the Insert button click event handler to perform the data insertion function as the project runs. The function of this piece of codes is to insert a new faculty record into our Oracle sample database CSE_DEPT using the Java runtime object method as this button is clicked.

7.4.1.2 Develop the Codes for the Insert Button Event Handler

In fact, there is no difference in the coding part for data insertion to a SQL Server or an Oracle database. You can open the Insert button click event handler from the project SQLSelectObject we built in the last section, copy the codes from that handler, and paste them into our current Insert button click event handler in the project

OracleSelectObject.

7.4 Perform Data Manipulations to Oracle Database Using Java Runtime Object 505

Figure 7.33. The modified FacultyFrame form window.

To confirm this data insertion, we can still use the codes inside the Select button click event handler, especially the codes inside the Runtime Object Method block. However, two important modifications need to be made to make them our desired validation methods:

1.Modify the codes inside the Select button click event handler to query two more columns, faculty_id and faculty_name, from the Faculty table.

2.Modify the ShowFaculty()method and divide it into two submethods,ShowFaculty() and DisplayImage().

During the development the codes for the Select button click event handler in

Chapter 6, we only query five columns without including the faculty_id and faculty_ name columns. Now we need to add these two columns for this data insertion validation.

Open the Select button click event handler and perform the modifications shown in Figure 7.34. The modified parts have been highlighted in bold.

Let’s have a closer look at this piece of modified codes to see how it works.

A.Two more columns, faculty_id and faculty_name, are added into the faculty text field array f_field since we need to query and display all columns from Faculty table to confirm the data insertion function.

B.Similarly, these two columns are added into the query string to enable them to be queried.

Now open the ShowFaculty() method and divide this method into two submethods, ShowFaculty() and DisplayImage(), which are shown in Figure 7.35. The modified parts have been highlighted in bold.