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

Practical Database Programming With Java

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

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

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

int numUpdated = 0;

AFacultyIDField.setEditable(false);

String query = "UPDATE Faculty f SET f.facultyName=?1, f.title=?2, f.office=?3, f.phone=?4, " + "f.college=?5, f.email=?6 WHERE f.facultyName=:FacultyName";

BOracleSelectWizardPUEntityManager.clear();

CfacultyQuery = OracleSelectWizardPUEntityManager.createQuery(query); facultyQuery.setParameter(1, FacultyNameField.getText()); facultyQuery.setParameter(2, TitleField.getText()); facultyQuery.setParameter(3, OfficeField.getText()); facultyQuery.setParameter(4, PhoneField.getText()); facultyQuery.setParameter(5, CollegeField.getText()); facultyQuery.setParameter(6, EmailField.getText()); facultyQuery.setParameter("FacultyName", ComboName.getSelectedItem()); String cFacultyName = (String)ComboName.getSelectedItem();

Djavax.persistence.EntityTransaction tr = OracleSelectWizardPUEntityManager.getTransaction(); if (!tr.isActive()){

tr.begin();

}

numUpdated = facultyQuery.executeUpdate(); tr.commit();

System.out.println("The number of updated row is: " + numUpdated); ComboName.addItem(FacultyNameField.getText());

ComboName.removeItem(cFacultyName);

}

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

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

A.To avoid the FacultyIDField to be modified, the setEditable() method is used to disable the editable ability of this text field.

B.In steps B, C, and D, we use the Oracle entity manager class to replace the SQL Server entity manager class to perform data manipulations against our Oracle database.

One point to be remembered is that you can copy the codes from the Select button click event handler from the project SelectQueryWizard and paste them into the Select button click event handler in the FacultyFrame form in our current OracleSelectWizard project to perform the validation of this data updating. The only modification is to replace the SQL Server entity manager SelectQueryWizardPUEntityManager with the Oracle entity manager OracleSelectWizardPUEntityManager in that piece of codes.

Now you can build and run the project to test the data updating action we build in this project.

In order to keep our database clean and neat, it is highly recommended to recover that updated record when you finished the testing of this updating action. Refer to Section 7.1.2.2 to complete this data recovery process.

A complete sample project OracleSelectWizard that can be used to perform data updating actions against our Oracle 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).

Next, let’s develop the codes to perform data deletion actions against our Oracle database.

7.2 Perform Data Manipulations to Oracle Database Using JPA Wizards 487

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

int numDeleted = 0;

String query = "DELETE FROM Faculty f WHERE f.facultyName=:FacultyName";

AOracleSelectWizardPUEntityManager.clear();

BfacultyQuery = OracleSelectWizardPUEntityManager.createQuery(query); facultyQuery.setParameter("FacultyName", ComboName.getSelectedItem()); String cFacultyName = (String)ComboName.getSelectedItem();

Cjavax.persistence.EntityTransaction tr = OracleSelectWizardPUEntityManager.getTransaction(); if (!tr.isActive()){

tr.begin();

}

numDeleted = facultyQuery.executeUpdate(); tr.commit();

System.out.println("The number of deleted row is: " + numDeleted);

ComboName.removeItem(cFacultyName);

}

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

7.2.3 Perform Data Deleting to Oracle Database Using JPA Wizards

Because of the data manipulation similarity between the SQL Server and Oracle database, you can use the codes in the Delete button click event handler in the project SelectQueryWizard we built in Section 7.1.3 to perform the data deletion action against our Oracle sample database. The only modification is to replace the SQL Server entity manager SelectQueryWizardPUEntityManager with the Oracle entity manager

OracleSelectWizardPUEntityManager in this piece of codes.

Open the Delete button click event handler, copy the codes from the Delete button in the project SelectQueryWizard we built in Section 7.1.3, and paste them into our current Delete button click event handler, as shown in Figure 7.19. The modified codes have been highlighted in bold.

The only modification to this piece of codes is to replace the SQL Server entity manager class with the Oracle entity manager class, as shown in steps A, B, and C in

Figure 7.19.

Now you can build and run the project to test the data deletion action against our Oracle sample database by deleting a faculty member Ying Bai.

In order to keep our sample database clean and neat, it is highly recommended to recover the 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 Oracle Database 10g Express Edition. To open this edition, go to Start\All Programs\Oracle Database 10g Express Edition\Go To Database Home Page, then enter the suitable username and password, such as CSE_DEPT and reback, to log in this page. Select the Object Browser > Browse > Tables to open the related four tables, click on the Data tab to modify or recover the desired records.

A complete sample project OracleSelectWizard that can be used to perform data deletion actions against our Oracle 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).

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

Now that we have finished the data manipulations using the JPA Wizards, we can move to the next part: Data manipulations using the Java runtime object method.

SECTION II INSERT, UPDATE AND DELETE DATA USING

JAVA RUNTIME OBJECTS METHOD

7.3 PERFORM DATA MANIPULATIONS TO SQL SERVER DATABASE USING JAVA RUNTIME OBJECT

As we did for the data query operations, in this section, we will discuss how to perform data manipulations using the Java runtime object method. Relatively speaking, there are some limitations in using the JAPI wizards to do the data manipulations. For instance, after the mapped entity has been built and the entity manager object has been created, the data manipulation can only be performed to that specified entity object or that data table. In other words, a defined or mapped entity object cannot perform data manipulations to any other entity object or data table.

Compared with the Java runtime object method, the JPA Wizards have the following shortcomings:

1.The details of the Java database programming is not clear as that of the Java runtime object method we will discuss in this section. Since most codes are created by JPA Wizards, quite a few details would be hidden to the users, and a complete and clear picture of Java database programming, especially for the structure and organization, is hard to be obtained and understood.

2.It is not flexible as that of the Java runtime object method we will discuss in this section. All of the codes must be created and developed before the project runs, or, statically, no modification can be performed during the project runs.

3.The compatibility is not desired as we expected. Since all projects are built based on NetBeans IDE and J2EE 5, they are not easy to be run at different platform when other IDE is utilized.

A good solution to these limitations is to use the Java runtime object to perform the data manipulations, and this will provide much more flexibilities and controllabilities to the data manipulations against the database, and allow a single object to perform multiple data manipulations against the target database.

Let’s first concentrate on the data insertion to our SQL Server database using the Java runtime object method.

7.3.1 Perform Data Insertion to SQL Server Database Using Java Runtime Object

We have provided a very detailed and clear discussion about the Java runtime object method in Section 6.3 in Chapter 6. Refer to that section to get more details for this topic. Generally, to use Java runtime object to perform data manipulations against our target database, the following six steps should be adopted:

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

1.Load and register the database driver using DriverManager class and Driver methods.

2.Establish a database connection using the Connection object.

3.Create a data manipulation statement using the createStatement() method.

4.Execute the data manipulation statement using the executeUpdate() or execute() method.

5.Retrieve and check the execution result of the data manipulations.

6.Close the statement and connection using the close() method.

Generally, SQL Server and Oracle databases are two popular database systems, and have been widely implemented in most commercial and industrial applications. In this and the following sections in this chapter, we will concentrate on these two database systems.

To save time and space, we can use and modify a project SQLSelectObject 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 SQLSelectObject 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 SQL Server sample database CSE_DEPT.

In Section 6.4.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 SQL Server 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.

7.3.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 SQLSelectObject:

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 SQLSelectObject, 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.

490 Chapter 7

Insert, Update, and Delete Data from Databases

 

Table 7.7. 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 SQLSelectObject projects in the NetBeans IDE, but they are different projects with different functions. The first SQLSelectObject 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\SQLSelectObjectPackage 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.7.

One point to be noted is that 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.20.

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 SQL Server sample database CSE_DEPT using the Java runtime object method as this button is clicked.

7.3.1.2 Develop the Codes for the Insert Button Event Handler

In Section 6.4.2.4 in Chapter 6, we have given a detailed discussion about the dynamic data query using the PreparedStatement object method. Refer to that section to get more details about that method. In this section, we will use that object to perform a dynamic faculty member insertion to the Faculty table in our sample database.

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

Figure 7.20. The modified FacultyFrame form window.

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

Aint numInsert = 0;

BString InsertQuery = "INSERT INTO Faculty (faculty_id, faculty_name, office, phone, " +

"college, title, email) VALUES (?, ?, ?, ?, ?, ?, ?)";

try {

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

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

EnumInsert = pstmt.executeUpdate();

}

F catch (SQLException e) {

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

}

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

HComboName.addItem(FacultyNameField.getText());

}

Figure 7.21. The added codes to the Insert button click event handler.

Open the Insert button click event handler and enter the codes that are shown in

Figure 7.21 into this handler.

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

A.A local integer variable numInsert is created, and it is used to hold the returned number of inserted row as the data insert action is performed.

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

B.An insert query string is created with seven positional dynamic parameters, which are associated with seven pieces of inserted faculty information.

C.A try…catch block is used to initialize and execute the data insertion action. First, a PreparedStatement instance is created using the Connection object that is located at the LogInFrame class with the insert query string as the argument.

D.The setString() method is used to initialize seven pieces of inserted faculty information, which are obtained from seven text fields and entered by the user as the project runs.

E.The data insertion function is performed by calling the executeUpdate() method. The running result of this method, which is an integer that equals to the number of rows that have been inserted into the database, is assigned to the local variable numInsert.

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

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

H.The new inserted faculty name is attached into the Faculty Name combo box to enable users to validate this data insertion later.

Before we can build and run the project to test the data insertion function, we should first figure out how to validate this data insertion. As we mentioned, we want to use the codes we built in the Select button click event handler to do this validation. Now let’s take care of this piece of codes to make it as our data insertion validation codes.

7.3.1.3 Develop the Codes for the Validation of the Data Insertion

To confirm and validate this data insertion, we can use the codes we built inside the Select button click event handler with some modifications. Two modifications are necessary:

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

Let’s do these modifications one by one.

During we developed 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 query.

Open the Select button click event handler and perform the modifications shown in Figure 7.22. 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.23. The modified parts have been highlighted in bold.

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

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

A javax.swing.JTextField[] f_field = {FacultyIDField, FacultyNameField, TitleField, OfficeField, PhoneField, CollegeField, EmailField};

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

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

DatabaseMetaData dbmd = LogInFrame.con.getMetaData(); String drName = dbmd.getDriverName();

String drVersion = dbmd.getDriverVersion();

msgDlg.setMessage("DriverName is: " + drName + ", Version is: " + drVersion); //msgDlg.setVisible(true);

PreparedStatement pstmt = LogInFrame.con.prepareStatement(query); pstmt.setString(1, ComboName.getSelectedItem().toString()); ResultSet rs = pstmt.executeQuery();

………

Figure 7.22. The modified codes for the Select button click event handler.

In Section 7.1.1.4, we have provided a detailed explanation about the modifications for this method, and refer to that section to get more information about this modification. The purpose of this modification is to allow the newly inserted faculty image to be displayed, either a new faculty image or a default one.

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

7.3.1.4 Build and Run the Project to Test the Data Insertion

Click on the Clean and Build Main Project button from the toolbar to build the project. Make sure that:

All faculty and students’ image files have been stored in the folder in which our project is located.

Our sample SQL Server database CSE_DEPT has been connected to our project.

Now click on the Run Main Project button to run the project. 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 fields, which is equivalent to a piece of new faculty information, and enter the default faculty image file into the Faculty Image text field, as shown in Figure 7.24.

Click on the Insert button to try to insert this new faculty record into the Faculty table in our sample database. Immediately, you can find that a debug message is displayed in the Output window, as shown in Figure 7.25.

Also. you can find that the new inserted faculty name has been added into the Faculty Name combo box if you click on the drop-down arrow from that box.

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

private boolean ShowFaculty(){ int maxNumber = 7; String fImage = null;

String[] fname = {"Ying Bai", "Black Anderson", "Satish Bhalla", "Steve Johnson", "Jenney King", "Alice Brown", "Debby Angles", "Jeff Henry"};

String[] fimage = {"Bai.jpg", "Anderson.jpg", "Satish.jpg", "Johnson.jpg", "King.jpg", "Brown.jpg", "Angles.jpg", "Henry.jpg"};

for (int i=0; i<=maxNumber; i++){

if (fname[i].equals((String)ComboName.getSelectedItem())){ fImage = fimage[i];

break;

}

}

if (fImage != null){ DisplayImage(fImage); return true;

}

else if (FacultyImageField.getText() != null){ fImage = FacultyImageField.getText(); DisplayImage(fImage); FacultyImageField.setText("");

return true;

}

else

return false;

}

private void DisplayImage(String facultyImage){ Image img;

int imgId = 1, timeout = 1000;

MediaTracker tracker = new MediaTracker(this);

MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);

img = this.getToolkit().getImage(facultyImage); Graphics g = ImageCanvas.getGraphics(); tracker.addImage(img, imgId);

try{

if(!tracker.waitForID(imgId,timeout)){ msgDlg.setMessage("Failed to load image"); msgDlg.setVisible(true);

}//end if }catch(InterruptedException e){

msgDlg.setMessage(e.toString()); msgDlg.setVisible(true);

}

g.drawImage(img, 0, 0, ImageCanvas.getWidth(), ImageCanvas.getHeight(), this);

}

Figure 7.23. The modified method ShowFaculty().

To confirm this data insertion, click on the new inserted faculty name from that combo box and click on the Select button to try to retrieve that newly inserted faculty record. The validation result is shown in Figure 7.26.

Our data insertion action is successful!

It is recommended to remove this inserted faculty from the Faculty table to keep our sample database neat and clean. Next, let’s perform the data updating action against our sample database using the Java runtime object method.

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

Figure 7.24. Insert a piece of new faculty information.

Figure 7.25. A successful data insertion message.

Figure 7.26. The data insertion validation result.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]