Perform Data Manipulations Using Updatable

Một phần của tài liệu practical database aprogramming with java (Trang 387 - 397)

JAVA RUNTIME OBJECTS METHOD

7.5 PERFORM DATA MANIPULATIONS USING UPDATABLE RESULTSET

7.5.2 Perform Data Manipulations Using Updatable

Generally, perform data manipulations using updatable ResultSet can be divided into the following three categories:

• Data insertion • Data updating • Data deleting

Different data manipulations need different operational steps, and Table 7.14 lists the most popular operational steps for these data manipulations.

It can be found from Table 7.14 that the data deleting is the easiest way to remove a piece of data from the database since it only needs one step to delete the data from both the ResultSet and the database. The other two data manipulations, data updating, and insertion, need at least two steps to complete that data manipulations.

The point to be noted is the data insertion action, in which the fi rst step moveToIn- sertRow() is exactly moved to a blank row that is not a part of the ResultSet, but related to the ResultSet. The data insertion is exactly occurred when the insertRow() method is called and the next commit command is executed.

Let ’ s start with the data insertion against our sample database fi rst. Since there is no difference between data manipulation for SQL Server and Oracle database, in the fol- lowing sections, we will use the Oracle database as our target database, and the same codes can be used for the SQL Server database as long as a valid database connection can be set up between our project and the target database.

7.5.2.1 Insert a New Row Using the Updatable ResultSet

To save time and space, we want to use and modify a project OracleSelectObject we built in Section 7.4 to make it as our new project to perform this data insertion action.

Perform the following operations to make it as our project:

Table 7.14. The operational steps of data manipulations using updatable resultset

Manipulation Type Steps

Data deleting Single step: Using the deleteRow() method of the ResultSet class.

Data updating Two steps:

Update the data in the ResultSet using the associated updateXXX() methods.

Copy the changes to the database using the updateRow() method.

Data insertion Three steps:

Move to the insert - row by calling the ResultSet moveToInsertRow() method.

Use the appropriate updateXXX() methods to update data in the insert - row.

Copy the changes to the database by calling the ResultSet insertRow() method.

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

2. Right click on the project OracleSelectObject we built in Section 7.4 and select the Set as Main Project item from the popup menu.

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

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

Perform the following modifi cations to this form:

1. Open the constructor of this class and add one more statement shown below into this constructor,

ComboMethod.addItem( “ Java Updatable ResultSet ” );

Your modifi ed codes in this constructor should match one that is shown in Figure 7.40 . The modifi ed part has been highlighted in bold.

2. Click on the Design button to switch back to the design view of the FacultyFrame form window, and double click on the Insert button to open its event handler. Enter the codes that are shown in Figure 7.41 into this handler to perform data insertion action against our Oracle database.

Let ’ s have a closer look at this piece of modifi ed 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 insertion.

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 insertion action. One point to be noted is that because of the limitation for the Updatable ResultSet under JDBC 2.0, you cannot use a star ( * ) following the SELECT to query all columns from the target table, instead you have to explicitly list all columns for this query. An option is to use the table aliases, such as SELECT f. * FROM TABLE f ... ... to do this kind of query.

D. A try … catch block is used to perform this data insertion. A PreparedStatement is created with two ResultSet parameters, TYPE_SCROLL_SENSITIVE and CONCUR_

Figure 7.40. The modifi ed codes for the constructor of the FacultyFrame class.

public FacultyFrame() { initComponents();

this.setLocationRelativeTo(null); // set the faculty Form at the center ComboMethod.addItem("JPA Wizards Method");

ComboMethod.addItem("Runtime Object Method");

ComboMethod.addItem("Java execute() Method");

ComboMethod.addItem("Java Callable Method");

ComboMethod.addItem("Java Updatable ResultSet");

ComboName.addItem("Ying Bai");

ComboName.addItem("Satish Bhalla");

ComboName.addItem("Black Anderson");

ComboName.addItem("Steve Johnson");

ComboName.addItem("Jenney King");

ComboName.addItem("Alice Brown");

ComboName.addItem("Debby Angles");

ComboName.addItem("Jeff Henry");

}

c07.indd 513

c07.indd 513 7/20/2011 11:12:08 AM7/20/2011 11:12:08 AM

www.traintelco.com

UPDATABLE , to defi ne 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. In order to insert a new row into this ResultSet, the moveToInsertRow() method is executed to move the cursor of the ResultSet to a blank row that is not a part of the ResultSet but is related to that ResultSet.

H. A sequence of updateString() methods are executed to insert desired columns to the associated columns in the ResultSet. The point to be noted is that different updateXXX()

Figure 7.41. The modifi ed codes for the Insert button click event handler.

private void cmdInsertActionPerformed(java.awt.event.ActionEvent evt) { int numInsert = 0;

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

String InsertQuery = "INSERT INTO Faculty (faculty_id, faculty_name, office, phone, " + "college, title, email) VALUES (?, ?, ?, ?, ?, ?, ?)";

try {

PreparedStatement pstmt = LogInFrame.con.prepareStatement(InsertQuery);

pstmt.setString(1, FacultyIDField.getText());

pstmt.setString(2, FacultyNameField.getText());

pstmt.setString(3, OfficeField.getText());

pstmt.setString(4, PhoneField.getText());

pstmt.setString(5, CollegeField.getText());

pstmt.setString(6, TitleField.getText());

pstmt.setString(7, EmailField.getText());

numInsert = pstmt.executeUpdate();

}

catch (SQLException e) {

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

msgDlg.setVisible(true);

} }

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

String query = "SELECT faculty_id, faculty_name, title, office, phone, college, email " + "FROM Faculty WHERE faculty_name = ?";

try {

PreparedStatement pstmt = LogInFrame.con.prepareStatement(query,

ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

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

ResultSet rs = pstmt.executeQuery();

rs.moveToInsertRow();

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

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

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

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

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

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

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

rs.insertRow();

rs.moveToCurrentRow(); // Go back to where we came from...

}

catch (SQLException e){

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

msgDlg.setVisible(true);

} }

System.out.println("The number of inserted row = " + numInsert);

ComboName.addItem(FacultyNameField.getText());

} A

B C

D E F G H

I J K

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 .

I. The insertRow() method is executed to update this change to the database. Exactly, this data updating would not happen until the next Commit command is executed.

J. The moveToCurrentRow() method is an optional and it return the cursor of the ResultSet to the original position before this data insertion is performed.

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

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

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 seven text fi elds, which is equivalent to a piece of new faculty information, and enter the default faculty image fi le into the Faculty Image text fi eld. To test this data insertion using the Updatable ResultSet, select the Java Updatable ResultSet from the Query Method combo box, as shown in Figure 7.42 . Then click on the Insert button to perform this data insertion.

To confi rm and validate this data insertion, two ways are available. First, let ’ s check this directly from this FacultyFrame form. Go to the Faculty Name combo box and you will fi nd that new inserted faculty name Tom Colin has been added into this box. Select this new inserted faculty member from that box and select the Runtime Object Method from the Query Method combo box followed with a clicking on the Select button to try to retrieve this new inserted faculty record. The returned faculty record is displayed, as shown in Figure 7.43 .

Figure 7.42. The newly inserted faculty record.

c07.indd 515

c07.indd 515 7/20/2011 11:12:08 AM7/20/2011 11:12:08 AM

www.traintelco.com

Now let ’ s try to open the Faculty table to confi rm 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 fi nd 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 inser- tion 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

Figure 7.43. The retrieved newly inserted faculty record.

Figure 7.44. The newly inserted faculty member.

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.

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

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

int numUpdated = 0;

String cFacultyName = null;

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

} }

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

String query = "SELECT faculty_name, title, office, phone, college, email " + "FROM Faculty WHERE faculty_name = ?";

try {

PreparedStatement pstmt = LogInFrame.con.prepareStatement(query,

ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

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

ResultSet rs = pstmt.executeQuery();

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

rs.updateRow();

}

cFacultyName = (String)ComboName.getSelectedItem();

}

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

} A

B C

D E F G

H I J

c07.indd 517

c07.indd 517 7/20/2011 11:12:09 AM7/20/2011 11:12:09 AM

www.traintelco.com

Let ’ s have a closer look at this piece of modifi ed 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 defi ne 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 updateS- tring() 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 fl ag 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 fi elds (without the Faculty ID fi eld), which is equivalent to a piece of updated faculty information, and enter the default faculty image fi le into the Faculty Image text fi eld. 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.

To confi rm 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 fi nd 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 confi rm this data updating in the second way, which is to open the Faculty table to confi rm 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,

Figure 7.46. The updated faculty information.

Figure 7.47. The retrieved updated faculty record.

c07.indd 519

c07.indd 519 7/20/2011 11:12:09 AM7/20/2011 11:12:09 AM

www.traintelco.com

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 fi nd 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 modifi ed 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.

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

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 defi ne 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 fi rst 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 fl ag 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 origi- nal faculty name, we need to temporarily store it to a local variable cFacultyName .

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

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

int numDeleted = 0;

String cFacultyName = null;

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

} }

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

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

try {

PreparedStatement pstmt = LogInFrame.con.prepareStatement(query,

ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

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

ResultSet rs = pstmt.executeQuery();

rs.absolute(1);

rs.deleteRow();

cFacultyName = (String)ComboName.getSelectedItem();

}

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

} A

B C D

E F G H I J

c07.indd 521

c07.indd 521 7/20/2011 11:12:09 AM7/20/2011 11:12:09 AM

www.traintelco.com

Một phần của tài liệu practical database aprogramming with java (Trang 387 - 397)

Tải bản đầy đủ (PDF)

(791 trang)