Practical Database Programming With Java
.pdf
506 Chapter 7 Insert, Update, and Delete Data from Databases
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.34. 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 new 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. Click on the Clean and Build Main Project button from the toolbar to build the
project. Then 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.36.
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.37.
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.
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 new inserted faculty record. The validation result will be displayed, and our data insertion action is successful!
To keep our database clean and neat, it is highly recommended to remove this newly inserted faculty record. You can do this data deletion using either the Object Browser in the Oracle Database 10g Express Edition or the Services window in NetBeans IDE 6.8.
Next, let’s perform the data updating action against our sample Oracle database using the Java runtime object method.
7.4 Perform Data Manipulations to Oracle Database Using Java Runtime Object 507
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.35. The modified method ShowFaculty().
7.4.2 Perform Data Updating to Oracle Database Using Java Runtime Object
There is no difference in the coding part for data updating against a SQL Server or an
Oracle database. You can open the Update button click event handler from the project SQLSelectObject we built in the last section, copy the codes from that handler, and paste themintoourcurrentUpdatebuttonclickeventhandlerintheprojectOracleSelectObject. For your convenience, we list this coding again in Figure 7.38.
508 Chapter 7 Insert, Update, and Delete Data from Databases
Figure 7.36. Insert a new faculty record.
Figure 7.37. A successful data insertion message.
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.38. The developed codes for the Update button click event handler.
7.4 Perform Data Manipulations to Oracle Database Using Java Runtime Object 509
For detailed explanations of this piece of codes, refer to Section 7.3.2.1 in this Chapter. To confirm this data updating, we can still use the codes inside the Select button click
event handler, especially the codes inside the Runtime Object Method block.
Now you can build and run the project to try to update a faculty member Ying Bai in our sample Oracle database. To keep our database clean and neat, it is highly recommended to recover the updated faculty member information. You can do that recovery job in two ways, using the Services window in the NetBeans IDE 6.8 or using the Object Browser in the Oracle Database 10g Express Edition. Refer to Table 7.2 in Section 7.1.3.2 to make this data recovery.
7.4.3 Perform Data Deleting to Oracle Database Using Java Runtime Object
Since no difference exists in the coding part for the data deleting from a SQL Server or an Oracle database, you can open the Delete 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 Delete button click event handler in the project OracleSelectObject. For your convenience, we list this coding again in Figure 7.39.
For detailed explanations of this piece of codes, refer to Section 7.3.3.1 in this chapter. Now you can build and run the project to try to delete a faculty member Ying Bai from our sample database.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. To confirm this data deletion, we can still use the codes inside the Select button click event handler, especially the codes inside the Runtime
Object Method block.
At this point, we have finished developing and building data manipulations to the Oracle database using the Java runtime object method. A complete sample project
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.39. The developed codes for the Delete button click event handler.
510 Chapter 7 Insert, Update, and Delete Data from Databases
OracleSelectObject that can be used to perform data insertion, updating, and 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).
Next, let’s take care of the data manipulations against our sample database using the updatable ResultSet object method.
7.5 PERFORM DATA MANIPULATIONS USING UPDATABLE RESULTSET
As we discussed in Section 6.4.2.5 in Chapter 6, a ResultSet object can be considered as a table of data representing a database result set, which is usually generated by executing a statement that queries the database.
The ResultSet interface provides getXXX() methods for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1. For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once.
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, it is possible to iterate through it only once and only from the first row to the last row. New methods in the JDBC 2.0 API make it possible to produce ResultSet objects that are scrollable and/or updatable.
Before we can use the ResultSet object to perform data manipulations against our sample database, let’s first have a clear picture about the ResultSet additional functionalities and categories supported in JDBC 2.0.
7.5.1 Introduction to ResultSet Enhanced Functionalities and Categories
ResultSet functionality in JDBC 2.0 includes enhancements for scrollability and positioning, sensitivity to changes by others, and updatability.
•Scrollability: the ability to move backward as well as forward through a ResultSet object. Associated with scrollability is the ability to move to any particular position in the ResultSet, through either relative positioning or absolute positioning.
•Positioning: the ability to move a specified number of rows forward or backward from the current row. Absolute positioning enables you to move to a specified row number, counting from either the beginning or the end of the ResultSet.
•Sensitivity: the ability to see changes made to the database while the ResultSet is open, providing a dynamic view of the underlying data. Changes made to the underlying columns values of rows in the ResultSet are visible.
Two parameters can be used to set up those properties of a ResultSet object when it is created, they are: ResultSet Type and Concurrency Type of a ResultSet.
Table 7.13 lists these types and their functions.
|
7.5 Perform Data Manipulations Using Updatable ResultSet |
511 |
Table 7.13. The resultset type and concurrency type |
|
|
|
|
|
ResultSet Type |
Functions |
|
|
|
|
Forward-only |
This is an JDBC 1.0 functionality. This type of ResultSet is not scrollable, |
|
|
not positionable, and not sensitive |
|
Scroll-sensitive |
This type of ResultSet is scrollable and positionable. It is also sensitive to |
|
|
underlying database changes. |
|
Scroll-insensitive |
This type of result set is scrollable and positionable, but not sensitive to |
|
|
underlying database changes. |
|
Concurrency type |
Functions |
|
Updatable |
Data updating, insertion, and deleting can be performed on the ResultSet |
|
|
and copied to the database. |
|
Read-only |
The result set cannot be modified in any way. |
|
|
|
|
Under JDBC 2.0, the Connection class has the following methods that take a ResultSet type and a concurrency type as input to define a newly created ResultSet object:
•Statement createStatement(int resultSetType, int resultSetConcurrency)
•PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
•CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency)
You can specify one of the following static constant values for ResultSet type:
•ResultSet.TYPE_FORWARD_ONLY
•ResultSet.TYPE_SCROLL_INSENSITIVE
•ResultSet.TYPE_SCROLL_SENSITIVE
And you can specify one of the following static constant values for concurrency type:
•ResultSet.CONCUR_READ_ONLY
•ResultSet.CONCUR_UPDATABLE
The following code fragment, in which conn is a valid Connection object and sql is a defined SQL query string, illustrates how to make a ResultSet that is scrollable and sensitive to updates by others, and that is updatable.
PreparedStatement pstmt = conn.prepareStatement
(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
After we have a basic and fundamental understanding about the ResultSet and its enhanced functionalities, now we can go ahead to perform data manipulations against our sample database using the Updatable ResultSet object.
512 Chapter 7 Insert, Update, and Delete Data from Databases
7.5.2 Perform Data Manipulations Using Updatable
ResultSet Object
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 first step moveToInsertRow() 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 first. Since there is no difference between data manipulation for SQL Server and Oracle database, in the following 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. |
|
|
7.5 Perform Data Manipulations Using Updatable ResultSet |
513 |
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");
}
Figure 7.40. The modified codes for the constructor of the FacultyFrame class.
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 modifications 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 modified codes in this constructor should match one that is shown in Figure 7.40. The modified 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 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 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_
514 Chapter 7 Insert, Update, and Delete Data from Databases
private void cmdInsertActionPerformed(java.awt.event.ActionEvent evt) { int numInsert = 0;
A 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);
}
}
Belse if (ComboMethod.getSelectedItem()=="Java Updatable ResultSet"){
CString query = "SELECT faculty_id, 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();
Grs.moveToInsertRow();
Hrs.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());
Irs.insertRow();
Jrs.moveToCurrentRow(); // Go back to where we came from...
|
} |
K |
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()); |
|
} |
Figure 7.41. The modified codes for the Insert button click event handler.
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.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()
7.5 Perform Data Manipulations Using Updatable ResultSet |
515 |
Figure 7.42. The newly inserted faculty record.
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 fields, which is equivalent to a piece of new faculty information, and enter the default faculty image file into the Faculty Image text field. 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 confirm 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 find 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.
