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

Practical Database Programming With Java

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

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

Figure 7.43. The retrieved newly inserted faculty record.

Figure 7.44. The newly inserted faculty member.

Now let’s try to open the Faculty table to confirm this data insertion. Open the Services window in the NetBeans IDE, and expand the Databases node and connect our Oracle database using the connection URL, jdbc:oracle:thin:@localhost:1521:XE [CSE_DEPT on CSE_DEPT]. Then expand this connected database, the CSE_DEPT and the Tables node, and right click on the Faculty table and select the View Data to this table. On the opened Faculty table, you can find that the new inserted faculty member, which has been highlighted in the table, has been there as shown in Figure 7.44.

Click on the Back and the Exit buttons to terminate our project, and our data insertion function is successful. It is highly recommended to remove this newly inserted faculty record from our sample database to keep our database clean and neat.

Next, let’s take care of the data updating action using the Updatable ResultSet object. As we did for the data insertion, we still want to use this FacultyFrame form

7.5 Perform Data Manipulations Using Updatable ResultSet

517

window to update one of faculty members in the Faculty table in our sample database CSE_DEPT.

7.5.2.2 Update a Row Using the Updatable ResultSet

Double click on the Update button from the FacultyFrame form window to open its event handler, and modify the codes that are shown in Figure 7.45 to perform the data updating function using the Updatable ResultSet object.

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

int numUpdated = 0; String cFacultyName = null;

A if (ComboMethod.getSelectedItem()=="Runtime Object Method"){

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);

}

}

Belse if (ComboMethod.getSelectedItem()=="Java Updatable ResultSet"){

CString query = "SELECT faculty_name, title, office, phone, college, email " +

"FROM Faculty WHERE faculty_name = ?";

try {

D PreparedStatement pstmt = LogInFrame.con.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

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

FResultSet rs = pstmt.executeQuery();

Gif (rs.absolute(1)) {

 

rs.updateString(1, FacultyNameField.getText());

 

rs.updateString(2, TitleField.getText());

 

rs.updateString(3, OfficeField.getText());

 

rs.updateString(4, PhoneField.getText());

 

rs.updateString(5, CollegeField.getText());

 

rs.updateString(6, EmailField.getText());

H

rs.updateRow();

 

}

I

cFacultyName = (String)ComboName.getSelectedItem();

 

}

J

catch (SQLException e){

 

msgDlg.setMessage("Error in Updatable ResultSet! " + e.getMessage());

 

msgDlg.setVisible(true);

 

}

 

}

 

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

 

ComboName.addItem(FacultyNameField.getText());

 

ComboName.removeItem(cFacultyName);

 

}

Figure 7.45. The modified codes for the Update button click event handler.

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

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

A.First, we add an if block to distinguish the Runtime Object Method and the Java Updatable ResultSet method to perform this data updating action.

B.An else if block is added with the same objective as step A.

C.The query string is created, and it is used to help to use the Updatable ResultSet object to do this data updating action.

D.A try…catch block is used to perform this data updating action. A PreparedStatement is created with two ResultSet parameters, TYPE_SCROLL_SENSITIVE, and CONCUR_ UPDATABLE, to define the ResultSet object to enable it to be scrollable and updatable, and enable it to perform data manipulations.

E.The setString() method is used to initialize the positional parameter in the query string.

F.The executeQuery() method is called to perform this query and return the query result to a newly created ResultSet object.

G.First, we need to identify the location of the row to be updated. Exactly, there is only one row that has been retrieved from our Faculty table and saved in the ResultSet, which is the default faculty member Ying Bai, and this row will be updated in this data updating action. Therefore, the absolute position for this row is 1. Then, a sequence of updateString() methods are executed to update desired columns to the associated columns in the ResultSet. The point to be noted is that different updateXXX() methods should be used if the target columns have the different data types, and the XXX indicate the associated data type, such as Int, Float, and Double.

H.The updateRow() method is executed to update this change to the database. Exactly, this data updating would not happen until the next Commit command is executed. Be aware that by default, the autocommit flag is set to true so that any operation run is committed immediately.

I.In order to update the selected faculty member, we need to remove the original faculty name and add the updated faculty name into the Faculty Name combo box when this data updating action is complete.To save the original faculty name, we need to temporarily store it to a local variable cFacultyName.

J.The catch block is used to track and collect any possible exception for this data updating action.

Now let’s build and run the project to test this data updating function.

Click on the Clean and Build Main Project button to build the project, and click on the Run Main Project button to run it.

Enter suitable username and password, such as jhenry and test, to the LogIn frame form and select the Faculty Information from the SelectFrame window to open the FacultyFrame form 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.

Modify six text fields (without the Faculty ID field), which is equivalent to a piece of updated faculty information, and enter the default faculty image file into the Faculty

Image text field. To test this data updating function using the Updatable ResultSet, select the Java Updatable ResultSet from the Query Method combo box, as shown in Figure 7.46. Then click on the Update button to perform this data updating.

7.5 Perform Data Manipulations Using Updatable ResultSet

519

Figure 7.46. The updated faculty information.

Figure 7.47. The retrieved updated faculty record.

To confirm and validate this data updating action, two ways are available. First, let’s check this directly from this FacultyFrame form. Go to the Faculty Name combo box and you will find that updated faculty name Susan Bai has been added into this box. Select this new updated faculty member from that box and select the Runtime Object Method from the Query Method combo box followed with clicking on the Select button to try to retrieve this updated faculty record. The returned faculty record is displayed, as shown in Figure 7.47.

Now let’s try to confirm this data updating in the second way, which is to open the Faculty table to confirm this data manipulation. Click on the Back and the Exit buttons to terminate our project. Then open the Services window in the NetBeans IDE, and expand the Databases node and connect our Oracle database using the connection URL,

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

Figure 7.48. The updated faculty record in the Faculty table.

jdbc:oracle:thin:@localhost:1521:XE [CSE_DEPT on CSE_DEPT] if it has not been connected. Then expand this connected database, the CSE_DEPT and the Tables node, and right click on the Faculty table and select the View Data to open this table. On the opened Faculty table, you can find that the updated faculty member, which has been highlighted, has been there as shown in Figure 7.48.

Our data updating function is successful.

It is highly recommended to recover this updated faculty record to the original one in our sample database to keep our database clean and neat. Refer to Table 7.8 in Section 7.3.3.2 to recover this updated faculty record.

Next, let’s take care of the data deletion action using the Updatable ResultSet object. As we did for the data updating, we still want to use this FacultyFrame form window to delete one of faculty members in the Faculty table in our sample database CSE_DEPT.

7.5.2.3 Delete a Row Using the Updatable ResultSet

In this section, we try to delete a default faculty record from our Faculty table using the Updatable ResultSet.

Double click on the Delete button from the FacultyFrame form window to open its event handler, and modify the codes that are shown in Figure 7.49 to perform the data deleting function using the Updatable ResultSet object.

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

A.First, we add an if block to distinguish the Runtime Object Method and the Java Updatable ResultSet method to perform this data deletion action.

B.An else if block is added with the same objective as step A.

C.The query string is created, and it is used to help the Updatable ResultSet object to do this data deleting action. The point to be noted here is that a table aliases f is used to represent the Faculty table and enable this query to retrieve all columns from that table. You cannot directly use the star (*) to do this query since it is prohibited in this enhanced ResultSet.

7.5 Perform Data Manipulations Using Updatable ResultSet

521

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

int numDeleted = 0;

String cFacultyName = null;

A if (ComboMethod.getSelectedItem()=="Runtime Object Method"){

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

PreparedStatement pstmt = LogInFrame.con.prepareStatement(query); pstmt.setString(1, ComboName.getSelectedItem().toString()); cFacultyName = (String)ComboName.getSelectedItem();

numDeleted = pstmt.executeUpdate();

}

catch (SQLException e) {

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

}

}

Belse if (ComboMethod.getSelectedItem()=="Java Updatable ResultSet"){

CString query = "SELECT f.* FROM Faculty f WHERE f.faculty_name = ?";

Dtry {

PreparedStatement pstmt = LogInFrame.con.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

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

FResultSet rs = pstmt.executeQuery();

Grs.absolute(1);

Hrs.deleteRow();

IcFacultyName = (String)ComboName.getSelectedItem();

}

Jcatch (SQLException e){

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

}

}

System.out.println("The number of deleted row = " + numDeleted); ComboName.removeItem(cFacultyName);

}

Figure 7.49. The modified codes for the Delete button click event handler.

D.A try…catch block is used to perform this data deleting action. A PreparedStatement is created with two ResultSet parameters, TYPE_SCROLL_SENSITIVE and CONCUR_ UPDATABLE, to define the ResultSet object to enable it to be scrollable and updatable, and furthermore enable it to perform data manipulations.

E.The setString() method is used to initialize the positional parameter in the query string.

F.The executeQuery() method is called to perform this query and return the query result to a newly created ResultSet object.

G.We need first to identify the location of the row to be deleted. In fact, there is only one row that has been retrieved from our Faculty table and saved in the ResultSet, which is the default faculty member Ying Bai, and this row will be deleted from this data deleting action. Therefore, the absolute position for this row is 1.

H.The deleteRow() method is executed to delete this record from the ResultSet and the database. In fact, this data deleting would not happen until the next Commit command is executed. Be aware that by default, the autocommit flag is set to true so that any operation run is committed immediately.

I.In order to delete the selected faculty member, we need to remove that faculty name from the Faculty Name combo box when this data deleting action is complete. To save the original faculty name, we need to temporarily store it to a local variable cFacultyName.

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

J.The catch block is used to track and collect any possible exception for this data deletion.

Now let’s build and run the project to test this data deleting function.

Click on the Clean and Build Main Project button to build the project, and click on the Run Main Project button to run it.

Enter suitable username and password, such as jhenry and test, to the LogIn frame form and select the Faculty Information from the SelectFrame window to open the FacultyFrame form 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.

To test this data deleting function using the Updatable ResultSet, select the Java Updatable ResultSet from the Query Method combo box. Then click on the Delete button to try to delete this default faculty member Ying Bai from our sample database.

Click on the Back and the Exit button to terminate our project.

To confirm and validate this data deleting action, open the Faculty table to confirm this data manipulation. To open the Faculty table, first open the Services window in the NetBeans IDE, and expand the Databases node and connect our Oracle database using the connection URL, jdbc:oracle:thin:@localhost:1521:XE [CSE_DEPT on CSE_ DEPT] if it has not been connected. Then expand this connected database, the CSE_DEPT and the Tables nodes, and right click on the Faculty table and select the View Data to open this table. On the opened Faculty table, you can find that the faculty member Ying Bai with the faculty_id of B78880 has been deleted from this table.

Our data deleting 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 this data recovery. An easy way to do this data recovery job is to use the Object Browser in the Oracle Database 10g Express Edition.

A complete sample project OracleSelectObject that contains the data insertion, updating, and deleting functions using the Updatable ResultSet object can be found from the folder DBProjects\Chapter 7 located at the Wiley ftp site (refer to Figure 1.2 in

Chapter 1).

Next, let’s discuss how to perform the data manipulations using the Callable statement.

7.6 PERFORM DATA MANIPULATIONS USING CALLABLE STATEMENTS

In Sections 6.4.5 and 6.4.5.2 in Chapter 6, we have provided a very detailed discussion about the data query from the Course table in our sample database using the CallableStatement method. Some basic and fundamental ideas and techniques using the

CallableStatement method and stored procedures have been given in detailed with some real sample projects. Refer to those sections to get clear pictures and understanding about the CallableStatement object. In this section, we will use this method to perform data manipulations against the Course table in our sample database CSE_DEPT.

7.6 Perform Data Manipulations Using Callable Statements 523

7.6.1 Perform Data Manipulations to SQL Server Database Using Callable Statements

Since the similarity between data manipulations for the SQL Server and the Oracle databases, we start with the data manipulations against the SQL Server database. First let’s take care of the data insertion to the Course table in our sample SQL Server database using the CallableStatement method.

7.6.1.1 Insert Data to SQL Server Database Using Callable Statements

In Section 6.4.1 in Chapter 6, we have built a project SQLSelectObject with some graphical user interface (GUI), including the CourseFrame form window, and we want to use that CourseFrame form window in that project with some modifications to make it as our GUI in this section. We will build the data insertion function with the CallableStatement method in the following procedures:

1.Modify the CourseFrame form window by adding one more Course ID text field to enable us to insert a new course record with this new course_id.

2.Build our stored procedure dbo.InsertNewCourse using the SQL Server Management Studio Express.

3.Develop the codes for the Insert button in the CourseFrame form window to execute the CallableStatement method to call our stored procedure dbo.InsertNewCourse to insert this new course record into the Course table in our sample database.

4.Confirm and validate this new course insertion using the codes we built for the Select button event handler.

Now let’s start from the first step.

7.6.1.1.1 Modify the CourseFrame Form Window To save time and space, we want to use and modify a project SQLSelectObject we built in Section 7.3.1 to make it as our new project to perform this data insertion action.

Perform the following operations to make it as our project:

1.Launch NetBeans IDE 6.8 and open the Projects window.

2.Right click on the project SQLSelectObject we built in Section 7.3.1 and select the Set

as Main Project item from the pop-up menu. If you cannot find this project, copy this project from the folder DBProjects\Chapter 7 located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1) and paste it to your default project folder JavaDBProject\Chapter 7. Then in the NetBeans IDE, go to File > Open Project menu item to open this project.

3.Double click on the CourseFrame.java to open the CourseFrame class.

4.Click on the Design button to open the CourseFrame form window.

Perform the following modifications to this form:

Add a Label and a Text Field into the Course Information panel with the properties shown in Table 7.15.

Add two buttons, Update and Delete, with the properties shown in Table 7.15. Also, rearrange these five buttons to the bottom of the CourseFrame form.

524 Chapter 7

Insert, Update, and Delete Data from Databases

 

Table 7.15. Objects and controls added into the courseframe window

 

 

 

 

 

 

 

Type

Variable Name

Text

editable

 

Title

Label

Label1

Course ID

 

 

 

Text Field

CourseIDField

 

checked

 

 

Button

cmdUpdate

Update

 

 

 

Button

cmdDelete

Delete

 

 

 

Figure 7.50. The modified CourseFrame form window.

Your finished CourseFrame form window should match one that is shown in Figure 7.50.

Before we can build the project using the CallableStatement method to perform the data manipulations, we need first to develop our stored procedure dbo.InsertNewCourse using the Microsoft SQL Server Management Studio Express.

7.6.1.1.2 Develop the Stored Procedure dbo.InsertNewCourse Recall that when we built our sample database CSE_DEPT in Chapter 2, there is no faculty name column in the Course table, and the only relationship that exist between the Faculty and the Course tables is the faculty_id, which is a primary key in the Faculty table, but a foreign key in the Course table. As the project runs, the user needs to insert a new course record based on the faculty name, not the faculty ID. Therefore, for this new course data insertion, we need to perform two queries with two tables: first, we need to make a query to the Faculty table to get the faculty_id based on the faculty name selected by the user, and second, we can insert a new course record based on the faculty_id we obtained from our first query. These two queries can be combined into a single stored procedure.

Launch the Microsoft SQL Server Management Studio Express by going to Start > All Programs > Microsoft SQL Server 2008 > SQL Server Management Studio. Click

7.6 Perform Data Manipulations Using Callable Statements 525

Figure 7.51. The newly stored procedure template.

the Connect button to open this studio server. On the opened studio, expand the Databasesand our sample database CSE_DEPTnodes.Then expand the Programmability node and right click on the Stored Procedures node, and select the New Stored Procedure to open a new stored procedure template, as shown in Figure 7.51.

You can use the Ctrl-Shift-M combination keys to enter all parameters for this stored procedure. However, an easy way to do that is to directly enter all parameters manually. On the opened newly stored procedure template, enter the following codes that are shown in Figure 7.52 into this stored procedure template as the body of our new stored procedure. The newly added codes have been highlighted in bold and indicated in steps A, B, and C, respectively. The codes in green color are comments for this stored procedure.

Go to File > Save SQLQuery1.sql to save this stored procedure.

Right click on any location inside our new stored procedure and select the Execute item to try to run it. Then right click on the Stored Procedures node from the Object

Explorer window and select the Refresh item to refresh it to get our newly created stored procedure dbo.InsertNewCourse. Right click on our newly stored procedure and select the Execute Stored Procedure to open the Execute Procedure wizard, which is shown in Figure 7.53.