JAVA RUNTIME OBJECTS METHOD
7.3 PERFORM DATA MANIPULATIONS TO SQL SERVER DATABASE USING JAVA RUNTIME OBJECT
7.3.1 Perform Data Insertion to SQL Server Database Using
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:
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.
c07.indd 489
c07.indd 489 7/20/2011 11:12:05 AM7/20/2011 11:12:05 AM
www.traintelco.com
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 fi rst
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 fi les to open the FacultyFrame.java fi le by double clicking on this fi le 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 fi elds 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 fi eld should be disabled when a data updating is performed because we will not update it during a faculty record updating process.
Your fi nished modifi ed 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.
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
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.
Figure 7.20. The modifi ed FacultyFrame form window.
Figure 7.21. The added codes to the Insert button click event handler.
private void cmdInsertActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
int numInsert = 0;
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);
}
System.out.println("The number of inserted row = " + numInsert);
ComboName.addItem(FacultyNameField.getText());
} A B
C D
E F
G H
c07.indd 491
c07.indd 491 7/20/2011 11:12:05 AM7/20/2011 11:12:05 AM
www.traintelco.com
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 fi elds 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 fi rst fi gure 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 confi rm and validate this data insertion, we can use the codes we built inside the Select button click event handler with some modifi cations. Two modifi cations 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 modifi cations one by one.
During we developed the codes for the Select button click event handler in Chapter 6 , we only query fi ve 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 modifi cations shown in Figure 7.22 . The modifi ed parts have been highlighted in bold.
Let ’ s have a closer look at this piece of modifi ed codes to see how it works.
A. Two more columns, faculty_id and faculty_name , are added into the faculty text fi eld array f_fi eld since we need to query and display all columns from Faculty table to confi rm 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 modifi ed parts have been highlighted in bold.
In Section 7.1.1.4 , we have provided a detailed explanation about the modifi cations for this method, and refer to that section to get more information about this modifi cation.
The purpose of this modifi cation is to allow the newly inserted faculty image to be dis- played, 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 fi les 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 user- name 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, 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 fi nd that a debug message is displayed in the Output window, as shown in Figure 7.25 .
Also. you can fi nd 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.
Figure 7.22. The modifi ed codes for the Select button click event handler.
private void cmdSelectActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
javax.swing.JTextField[] f_field = {FacultyIDField, FacultyNameField, TitleField, OfficeField, PhoneField, CollegeField, EmailField};
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();
………
A B
c07.indd 493
c07.indd 493 7/20/2011 11:12:05 AM7/20/2011 11:12:05 AM
www.traintelco.com
To confi rm 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.
Figure 7.23. The modifi ed method ShowFaculty().
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.24. Insert a piece of new faculty information.
Figure 7.25. A successful data insertion message.
Figure 7.26. The data insertion validation result.
c07.indd 495
c07.indd 495 7/20/2011 11:12:06 AM7/20/2011 11:12:06 AM
www.traintelco.com