
Practical Database Programming With Java
.pdf
536 Chapter 7 Insert, Update, and Delete Data from Databases
Figure 7.62. The running result of the data updating action.
Classroom: TC-303
Credit: 3
Enrollment: 28
Then click on the Update button to update this course record in the Course table in our sample database. To confirm and validate this data updating, click on the Select button to try to retrieve all courses taught by the selected faculty member Ying Bai. The running result is shown in Figure 7.62.
Another way to confirm this data updating action is to open the Course table using the Services window in the NetBeans IDE. To do that, open the Services window and expand the Databases node and connect to our SQL Server database by right clicking on that URL and selecting the Connect item. Then expand that connected URL and our CSE_DEPT database node, dbo schema and Tables nodes. Right click on the Course table and select the View Data to open this table. Click on the Next Page tab, and you can find that the course CSE-549 has been updated and displayed at the last line on this Course table, as shown in Figure 7.63.
Our data updating using the CallableStatement object is successful.
Next, let’s handle the data deleting using the CallableStatement object method.
7.6.1.3 Delete Data from SQL Server Database Using Callable Statements
In this section, we try to delete a course record from our Course table using the CallableStatement object method. First, let’s develop the stored procedure using Microsoft
SQL Server Management Studio Express.
7.6.1.3.1 Develop the Stored Procedure dbo.DeleteCourse Launch the Microsoft SQL Server Management Studio Express by going to Start > All Programs > Microsoft

7.6 Perform Data Manipulations Using Callable Statements 537
Figure 7.63. The updated course CSE-549 in the Course table.
SQL Server 2008 > SQL Server Management Studio. Click the Connect button to open this studio server. On the opened studio, expand the Databases and our sample database CSE_DEPT nodes. Then expand the Programmability node and right click on the Stored Procedures node, select the New Stored Procedure to open a new stored procedure template.
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 codes that are shown in Figure 7.64 into this stored procedure template as the body of our newly stored procedure dbo.DeleteCourse. You can create this piece of codes manually or by using the Query Designer as we did in the last section for the stored procedure dbo. UpdateCourse.
Let’s have a closer look at this piece of codes to see how it works.
A.The only input to this stored procedure is the course_id that is a primary key to the Course table. Here we use @CourseID as a dynamic parameter for this stored procedure.
B.The DELETE statement is created with the @CourseID as this deleting criterion.
Save this stored procedure by going to the File > Save SQLQuery3.sql and click on the Save button. Right click on any location inside our newly stored procedure and select the Execute item to try to run it. Then right click on the Stored Procedures node in the Object Explorer window and select the Refresh item to show our newly built stored procedure dbo.DeleteCourse.
Now let’s run this stored procedure to test its functionality. Right click on our newly created stored procedure dbo.DeleteCourse from the Object Explorer window and

538Chapter 7 Insert, Update, and Delete Data from Databases
--================================================
SET ANSI_NULLS ON GO
SET QUOTED_IDENTIFIER ON GO
--=============================================
-- Author: |
Y. Bai |
-- Create date: |
Aug 3, 2010 |
-- =============================================
CREATE PROCEDURE dbo.DeleteCourse
-- Add the parameters for the stored procedure here
A @CourseID VARCHAR(50)
AS BEGIN
--SET NOCOUNT ON added to prevent extra result sets from
--interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
BDELETE FROM Course
WHERE (course_id = @CourseID)
END
GO
Figure 7.64. The codes for the stored procedure dbo.DeleteCourse.
select the Execute Stored Procedure item to open the Execute Procedure wizard. Enter the following data into the associated Value column to this wizard:
• @CourseID: CSE-549
Click on the OK button to run this stored procedure. The running result is shown in Figure 7.65. It can be found that a successful running message is displayed in the Output windows (1 row(s) affected), and the Query executed successfully statement is also displayed in the status bar at the bottom of this window.
It is highly recommended to recover this deleted course record to its original values since we need to call the CallableStatement object to run this stored procedure again when we test our project later. You can do this recovery job inside the Microsoft SQL
Server Management Studio Express by opening the Course table. Refer to Table 7.16 to recover this deleted course record.
Now close the Microsoft SQL Server Management Studio, since we have finished building and testing the stored procedure.
Next, we need to build our codes for the Delete button click event handler in the CourseFrame form to call this stored procedure to perform this data-deleting action.
7.6.1.3.2 Develop the Codes for the Delete Button Click Event Handler Double click on the Delete button on the CourseFrame form window to open its event handler and enter the codes that are shown in Figure 7.66 into this handler.
Table 7.16. The deleted course record in the course table
course_id |
course |
credit |
classroom |
schedule |
enrollment |
faculty_id |
|
CSE-549 |
Intelligent Controls |
3 |
TC-303 |
M-W-F: 11:00 – 11:50 am |
28 |
B78880 |

7.6 Perform Data Manipulations Using Callable Statements 539
Figure 7.65. The running result of the stored procedure dbo.DeleteCourse.
private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) {
Aif (ComboMethod.getSelectedItem()=="Java Callable Method"){
BCallableStatement cstmt = null; try{
CString query = "{call dbo.DeleteCourse(?)}";
Dcstmt = LogInFrame.con.prepareCall(query);
Ecstmt.setString(1, CourseList.getSelectedValue().toString());
Fcstmt.execute();
}
G catch (SQLException e){
msgDlg.setMessage("Error in CallableStatement! " + e.getMessage()); msgDlg.setVisible(true);
}
}
H CourseIDField.setText(null);
}
Figure 7.66. The codes for the Delete button click event handler.
Let’s have a close look at this piece of codes to see how it works.
A.An if block is used to distinguish whether the Java Callable Method has been selected.
B.If it is, a new CallableStatement instance is declared.
C.Atry…catchblock is used to perform this data deleting action using the CallableStatement method. The CallableStatement query string is created. Refer to Section 6.4.5.2 in Chapter

540 Chapter 7 Insert, Update, and Delete Data from Databases
6 to get more detailed information about the structure and protocol of a CallableStatement query string. This is a dynamic query string with one positional parameter related to a new course; therefore, a question mark is used as the position holder for this parameter.
D.A new CallableStatement instance is created by calling the prepareCall() method that is defined in the Connection class.
E.The dynamic query string is initialized with a positional parameter, and the value of this parameter is selected by the user from the CourseList listbox.
F.The CallableStatement instance is executed to call the stored procedure we built in the last section to delete the selected course record in the Course table in our sample database.
G.The catch block is used to track and collect any possible exception for this data deleting.
H.The deleted course_id is removed from the Course ID field to indicate this deleting action.
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 the project.
Enter suitable username and password, such as jhenry and test, to the LogIn frame form and select the Course Information from the SelectFrame window to open the CourseFrame form window. Make sure that the Java Callable Method has been selected from the Query Method combo box.Then click on the Select button to query the default course information for the selected faculty member Ying Bai.
Now select the course CSE-549 from the CourseList listbox and click on the Delete button to try to delete this course from the Course table in our sample database.
To confirm and validate this data deletion action, click on the Select button again to try to retrieve all courses taught by the default faculty Ying Bai. It can be found that there is no CSE-549 course in the CourseList listbox, and this means that the course CSE-549 has been deleted from the Course table. You can also confirm this data deleting action by opening the Course table using the Services window in the NetBeans IDE.
At this point, we have finished developing and building data manipulations project using CallableStatement object method. A complete project SQLSelectObject that contains all three data manipulation actions to SQL Server database can be found at the folder DBProjects\Chapter 7 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).
Next,let’shandlethedatamanipulationstoOracledatabaseusingtheCallableStatement object method.
7.6.2 Perform Data Manipulations to Oracle Database Using Callable Statements
Basically, there is no significant difference between the data manipulations to SQL Server and Oracle databases using the CallableStatement object. The only differences are the connected database and stored procedures. As long as a valid connection to the selected database has been set up and all stored procedures are built using the Oracle Database 10g XE, all codes developed in Section 7.6.1 can be used for Oracle database without problem.

7.6 Perform Data Manipulations Using Callable Statements 541
To save time and space, we can use and modify an Oracle project OracleSelectObject we built in Section 7.4 to make it as our new project to perform the data manipulations using the CallableStatement method.
In this section, we want to use the CourseFrame form to perform data manipulations, such as data insertion, updating, and deleting against the Course table in our Oracle sample database. The only modifications to this form are:
1.The CourseFrame form window
2.Three Oracle stored procedures
The first modification enables us to have all text fields and buttons in the CourseFrame form to allow us to perform all three kinds of data manipulations. The second modification enables us to call these Oracle stored procedures using the CallableStatement to perform the data manipulations. Let’s start with the first modification.
7.6.2.1 Modify the CourseFrame Form Window
Refer to Section 7.6.1.1.1 to complete this CourseFrame form modification.Your modified CourseFrame form window should match one that is shown in Figure 7.67.
Now, you can open the project SQLSelectObject we built in the last section and copy the codes from the Insert, Update, and Delete button click event handlers in the CourseFrame form and paste them into the associated Insert, Update, and Delete button click event handlers in our current modified CourseFrame form one by one. To open the project SQLSelectObject, you can go to the folder DBProjects\Chapter 7 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).
Now, let’s do some modifications to these three event handlers to make them match to the data actions in Oracle database.
Figure 7.67. The modified CourseFrame form window.

542 Chapter 7 Insert, Update, and Delete Data from Databases
The only modification we need to do is to remove the prefix dbo for each CallableStatement query string in three event handlers. As you remember, when we built our three stored procedures in Microsoft SQL Server Management Studio Express, dbo. InsertNewCourse, dbo.UpdateCourse and dbo.DeleteCourse, all of these stored procedures are prefixed with a prefix dbo, which is a SQL Server database schema. However, when we build those stored procedures in Oracle database, we do not need those prefixes anymore. Therefore, we need to remove these prefixes before each stored procedure in the CallableStatement query string.
Open these three event handlers and remove the prefix dbo from each query string in our pasted codes. After this deletion, our three stored procedures are named
InsertNewCourse(), UpdateCourse(), and DeleteCourse(), respectively. Next, we will build three stored procedures with the identical names of those three stored procedures using the Object Browser in Oracle Database 10g Express Edition.
7.6.2.2 Build Three Oracle Stored Procedures
Recall in Section 6.5.4.1 in Chapter 6, we provided a very detailed discussion about the package and stored procedures in the Oracle database environment. Refer to that section to get more detailed information about how to create a package and stored procedure in Oracle database. In this section, we will provide some discussions about how to create Oracle stored procedures, InsertNewCourse(), UpdateCourse(), and DeleteCourse().
From Section 6.5.4.1, we got an idea about the difference between an Oracle stored procedure and an Oracle package. The key issue is that an Oracle stored procedure never return any data, but an Oracle package must return some data. For our course data insertion, updating, and deleting, we do not need to return any data. Based on this criterion, let’s start to build our Oracle stored procedures to perform these three kinds of data actions against our sample Oracle database.
7.6.2.2.1 Create the InsertNewCourse Stored Procedure Open the Oracle Database 10g XE home page by going to Start|All Programs|Oracle Database 10g Express Edition|Go To Database Home Page items. Log in as a user by entering
CSE_DEPT into the Username box and the password reback into the Password box. Click the Object Browser and select Create|Procedure to open the Create Procedure window.
Enter the procedure name, InsertNewCourse, into the Procedure Name field, and keep the Include Arguments checkbox checked, then click on the Next button.
In the Arguments page, enter seven pieces of new course information into seven Argument fields. Refer to Section 2.11.2.3 in Chapter 2 for data types of these seven data. Your finished Arguments page should match one that is shown in Figure 7.68.
Click on the Next button to go to the procedure-defining page.
Enter the codes that are shown in Figure 7.69 into this new procedure as the body of the procedure using the language that is called Procedural Language Extension for SQL or PL-SQL. Then click on the Next and the Finish buttons to confirm creating of this procedure.
Your finished Procedure-Define page is shown in Figure 7.70.
Seven input parameters are listed at the beginning of this procedure with the keyword IN to indicate that these parameters are inputs to the procedure.The intermediate parameter facultyID is obtained from the first query in this procedure from the Faculty table.

7.6 Perform Data Manipulations Using Callable Statements 543
Figure 7.68. The finished Arguments page.
SELECT faculty_id INTO facultyID FROM Faculty
WHERE faculty_name = FacultyName;
INSERT INTO Course VALUES (CourseID, Course, Credit,
Classroom, Schedule, Enroll, facultyID);
Figure 7.69. The body of the stored procedure.
The data type of each parameter is indicated after the keyword IN, and it must be identical with the data type of the associated data column in the Course table. An IS command is attached after the procedure header to indicate that a query result, faculty_id, will be held by a local variable facultyID declared later.
Two queries are included in this procedure. The first query is used to get the faculty_ id from the Faculty table based on the input parameter FacultyName, and the second query is to insert seven input parameters into the Course table based on the faculty_id obtained from the first query.A semicolon must be attached after each PL-SQL statement and after the command end.
One important issue is that you need to create one local variable facultyID and attach it after the IS command as shown in Figure 7.71, and this coding has been highlighted with the background color. Click the Edit button to add this local variable after the IS command. This local variable is used to hold the returned faculty_id from the execution of the first query.
Another important issue in distributing the input parameters or arguments in an INSERT command is that the order of those parameters or arguments must be identical

544 Chapter 7 Insert, Update, and Delete Data from Databases
Figure 7.70. The finished procedure-define page.
facultyID VARCHAR2(10);
Figure 7.71. The modified stored procedure.
with the order of the data columns in the associated data table. For example, in the
Course table, the order of the data columns is: course_id, course, credit, classroom, schedule, enrollment, and faculty_id. Accordingly, the order of input parameters placed in the INSERT argument list must be identical with the data columns’ order displayed above.

7.6 Perform Data Manipulations Using Callable Statements 545
Figure 7.72. The finished Arguments page.
To make sure that this procedure is error free, we need to compile it first. Click the Compile button to compile and check our procedure. A successful compilation message should be displayed if our procedure is a bug-free stored procedure.
Next, let’s continue to build our second stored procedure UpdateCourse().
7.6.2.2.2 Create the UpdateCourse Stored Procedure Click on the Create button located at the upper-right corner of this InsertNewCourse() procedure window and select the Procedure to open a new procedure page.
Enter UpdateCourse into the Procedure Name field and keep the Include Arguments checkbox checked, then click on the Next button.
In the Arguments page, enter six pieces of updated course information into six Argument fields. Refer to Section 2.11.2.3 in Chapter 2 for data types of these seven data. Your finished Arguments page should match one that is shown in Figure 7.72.
A point to be noted is that some input parameters, such as Course, Schedule, Classroom, Credit, and Enroll, are closely identical with the names of associated columns in our Course table. The only difference between them is that the first letters of those input parameters are capital, but the columns’ names are not. However, as you know, the PL-SQL language is a case-insensitive language, and this difference would be removed when the stored procedure is executed. To avoid this confusion between the input parameters and names of columns in the Course table, we prefixed an in before those input parameters to distinguish them with the names of associated columns in our Course table.
Click on the Next button to go to the procedure-defining page.
Enter the codes that are shown in Figure 7.73 into this new procedure as the body of the procedure using the PL-SQL language. Then click on the Next and the Finish buttons to confirm creating of this procedure.