Practical Database Programming With Java
.pdf
526 Chapter 7 Insert, Update, and Delete Data from Databases
USE [CSE_DEPT] GO
/****** Object: StoredProcedure [dbo].[InsertNewCourse] Script Date: 5/14/2010 17:12:23 ******/
--================================================
SET ANSI_NULLS ON GO
SET QUOTED_IDENTIFIER ON GO
--=============================================
-- Author: |
Y. Bai |
--Create date: May, 2010
--Description: SQL Server stored procedure
--=============================================
ACREATE PROCEDURE dbo.InsertNewCourse
-- Add the parameters for the stored procedure here
B@FacultyName VARCHAR(50), @CourseID VARCHAR(50), @Course text,
@Schedule text, @Classroom text, @Credit int, @Enroll int
AS
BEGIN
--SET NOCOUNT ON added to prevent extra result sets from
--interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
CDECLARE @FacultyID AS VARCHAR(50)
SET @FacultyID = (SELECT faculty_id FROM Faculty WHERE (faculty_name = @FacultyName)) INSERT INTO Course(course_id, course, schedule, classroom, credit, enrollment, faculty_id) VALUES (@CourseID, @Course, @Schedule, @Classroom, @Credit, @Enroll, @FacultyID)
END
GO
Figure 7.52. The codes for our new stored procedure.
Enter a set of parameters shown in Figure 7.53 into the associated Value columns as a new course record, and click on the OK button to run this stored procedure to test its functionality.
The test result is shown in Figure 7.54. It can be found that a successful message, 1 row(s) affected, is displayed in the Output window.
It is highly recommended to delete this newly inserted course record from our Course table since we need to keep our sample database clean and neat. Another point is that we need to call this stored procedure later from our project to perform this data insertion. In order to avoid a duplicated data insertion, we need to remove this course record now.You can do this data deletion by opening the Course table from the NetBeans IDE or opening the Microsoft SQL Server Management Studio Express.
Now close the Microsoft SQL Server Management Studio Express, and we can continue to develop the codes for the CallableStatement method to call this stored procedure to perform a new course insertion action against our sample database.
7.6 Perform Data Manipulations Using Callable Statements 527
Figure 7.53. The opened Execute Procedure wizard.
7.6.1.1.3 Develop the Codes for the Insert Button Click Event Handler The function of this piece of codes is to call the stored procedure we built in the last section to perform a new course insertion to the Course table in our sample database. The insertion criterion is the faculty member selected from the Faculty Name combo box. The newly inserted course record can be retrieved and displayed in the CourseList listbox by clicking on the Select button to confirm this data insertion.
Generally, the sequence to run a CallableStatement to perform a stored procedure is:
1.Build and formulate the CallableStatement query string
2.Create a CallableStatement object
3.Set the input parameters
4.Register the output parameters
5.Execute CallableStatement
6.Retrieve the running result by using different getXXX() method
Since we do not have any output result to be returned from this stored procedure, therefore, we can skip steps 4 and 6.
Now let’s develop the codes for this event handler to perform the calling of the stored procedure we built in the last section to perform this data insertion function.
528 Chapter 7 Insert, Update, and Delete Data from Databases
Figure 7.54. The running result of the stored procedure.
Double click on the Insert button on the CourseFrame form window to open its event handler and enter the codes that are shown in Figure 7.55 into this handler.
Let’s have a closer 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.A try…catch block is used to perform this data insertion using the CallableStatement method. The CallableStatement query string is created. Refer to Section 6.4.5.2 in Chapter 6 to get more detailed information about the structure and protocol of a CallableStatement query string. This is a dynamic query string with seven pieces of positional inserting information related to a new course; therefore, seven question marks are used as the position holders for those parameters.
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 seven positional parameters, and the values of those parameters are entered by the user into the associated course-related text fields.
F.The CallableStatement instance is executed to call the stored procedure we built in the last section to insert a new course record into the Course table in our sample database.
G.The catch block is used to track and collect any possible exception for this data insertion process.
7.6 Perform Data Manipulations Using Callable Statements 529
private void cmdInsertActionPerformed(java.awt.event.ActionEvent evt) {
Aif (ComboMethod.getSelectedItem()=="Java Callable Method"){
BCallableStatement cstmt = null;
try{
CString query = "{call dbo.InsertNewCourse(?, ?, ?, ?, ?, ?, ?)}";
Dcstmt = LogInFrame.con.prepareCall(query);
Ecstmt.setString(1, ComboName.getSelectedItem().toString()); cstmt.setString(2, CourseIDField.getText()); cstmt.setString(3, CourseField.getText());
cstmt.setString(4, ScheduleField.getText()); cstmt.setString(5, ClassroomField.getText()); cstmt.setString(6, CreditField.getText()); cstmt.setString(7, EnrollField.getText());
Fcstmt.execute();
}
G catch (SQLException e){
msgDlg.setMessage("Error in CallableStatement! " + e.getMessage()); msgDlg.setVisible(true);
}
}
}
Figure 7.55. The codes for the Insert button click event handler.
Now let’s build and run the project to test this data insertion 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 enter the following data into seven text fields as a new course record for the selected faculty member:
Course ID: CSE-549
Course: Fuzzy Systems
Schedule: T-H: 1:30–2:45 pm
Classroom: TC-302
Credit: 3
Enrollment: 25
Then click on the Insert button to insert this course record into the Course table in our sample database.
To confirm and validate this data insertion, 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.56, and you can see that the newly inserted course CSE-549 is indeed added to the database and displayed in the CourseList listbox.
Click on the Back and the Exit buttons to terminate our project.
530 Chapter 7 Insert, Update, and Delete Data from Databases
Figure 7.56. The running result for the data insertion validation.
Another way to confirm this data insertion 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 select 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 inserted to the last line on this Course table, as shown in Figure 7.57.
Our data insertion using the CallableStatement object is successful.
Next, let’s handle the data updating using the CallableStatement object method.
7.6.1.2 Update Data to SQL Server Database Using Callable Statements
Before we can build the project using the CallableStatement method to perform the data manipulations, we need first to develop our stored procedure dbo.UpdateCourse using the Microsoft SQL Server Management Studio Express.
7.6.1.2.1 Develop the Stored Procedure dbo.UpdateCourse Generally, we do not need to update a course_id when we update a course record in the Course table since a better way to do that is to insert a new course record and delete the old one. The main reason for this is that a very complicated operation would be performed if the course_id were updated, since it is a primary key in the Course table and foreign keys in the StudentCourse table. To update a primary key, one needs to update foreign keys first in the child tables and then update the primary key in the parent table. This will make our updating operation very complicated and easy to be confused. In order to avoid this confusion, in this section, we will update a course record by changing any other columns except the course_id, and this is a popular way to update a table and widely implemented in most database applications.
7.6 Perform Data Manipulations Using Callable Statements 531
Figure 7.57. The newly inserted new course CSE-549.
Launch the Microsoft SQL Server Management Studio Express by going to Start > All Programs > Microsoft SQL Server 2008 > SQL Server Management Studio. Click the Connect button to open this studio server. On the opened studio, expand the Databasesand our sample database CSE_DEPTnodes.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 new stored procedure template, enter the codes that are shown in Figure 7.58 into this stored procedure template as the body of our new stored procedure dbo.UpdateCourse.
An easy way to do the UPDATE statement coding part is to use the Design Query in Editor wizard. In this section, we try to use this wizard to build the UPDATE statement for this query.
To open this wizard, right click on any blank space in the opened new stored procedure template and select the Design Query in Editor item from the pop-up menu. Click on the Close button for the Add Table dialog box to close this dialog. Perform the following operations to build this UPDATE statement.
1.Select the SELECT ... FROM codes from the bottom pane to delete them.
2.Right click on the bottom pane and select the Change Type item and select the Update item from the pop-up menu.
3.Right click on the top pane and select the Add Table item. Select the Course table and click on the Add button. Click on the Close button to close this Add Table dialog.
4.Click on the row under the Column in the mid-pane and select the Course item.
532Chapter 7 Insert, Update, and Delete Data from Databases
--================================================
SET ANSI_NULLS ON GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Y. Bai
-- =============================================
CREATE PROCEDURE dbo.UpdateCourse
-- Add the parameters for the stored procedure here
A@CourseID VARCHAR(50), @Course text,
@Schedule text, @Classroom text, @Credit int,
@Enroll int
AS BEGIN
--SET NOCOUNT ON added to prevent extra result sets from
--interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
BUPDATE Course
SET course = @Course, schedule = @Schedule, classroom = @Classroom, credit = @Credit, enrollment = @Enroll
WHERE (course_id = @CourseID)
END
GO
Figure 7.58. The codes for the dbo.UpdateCourse stored procedure.
5.In the similar way to click on the row under the Course item and select the Schedule item in the Column. Continue in this way to select all other items, Classroom, Credit, Enrollment, and course_id.
6.Uncheck the check box for the row course_id in the Set column and type a question mark “?” in the Filter column for the course_id row, and then press the Enter key in your keyboard.
7.Modify the dynamic parameter’s name from @Param1 to @CourseID.
8.Enter the updated values to the associated New Value column. The point to be noted is that all of these updated values’ names must be identical with those input parameters to the stored procedure we built in step A in Figure 7.58.
Your finished Query Designer wizard should match one that is shown in Figure 7.59. Click on the OK button to create this UPDATE statement codes that have been highlighted in the background color in step B in Figure 7.58.
Let’s have a closer look at this piece of codes to see how it works.
A.Six input parameters to this stored procedure are declared first with the associated data types. These parameters must be identical with those parameters in the CallableStatement query string we will build later to enable the CallableStatement to recognize them when it is executed to perform the data updating action in our project.
B.The UPDATE statement we built using the Query Designer wizard is attached here, and the query criterion course_id is obtained from the CourseList listbox.
7.6 Perform Data Manipulations Using Callable Statements 533
Figure 7.59. The Finished Query Designer wizard.
Save this stored procedure by going to the File > Save SQLQuery2.sql and click on the Save button. Right click on any location inside our new 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.UpdateCourse.
Now let’s run this stored procedure to test its functionality. Right click on our newly created stored procedure dbo.UpdateCourse from the Object Explorer window and select the Execute Stored Procedure item to open the Execute Procedure wizard. Enter the following data into the associated Value columns to this wizard:
• |
@CourseID: |
CSE-549 |
• |
@Course: |
Intelligent Controls |
•@Schedule: M-W-F: 11:00–11:50 am
•@Classroom: TC-303
• |
@Credit: |
3 |
• |
@Enrollment: 28 |
|
Click on the OK button to run this stored procedure. The running result is shown in Figure 7.60. 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 updated 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
534 Chapter 7 Insert, Update, and Delete Data from Databases
Figure 7.60. The running result of the stored procedure dbo.UpdateCourse.
Server Management Studio Express by opening the Course table. Close the Microsoft SQL Server Management Studio Express since we have finished building and testing the stored procedure.
Now let’s build our codes for the Update button click event handler in the CourseFrame form to call this stored procedure to perform this data updating action.
7.6.1.2.2 Develop the Codes for the Update Button Click Event Handler Double click on the Update button on the CourseFrame form window to open its event handler and enter the codes that are shown in Figure 7.61 into this 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…catchblockisusedtoperformthisdataupdatingactionusingtheCallableStatement method. The CallableStatement query string is created. Refer to Section 6.4.5.2 in Chapter 6 to get more detailed information about the structure and protocol of a CallableStatement query string. This is a dynamic query string with six pieces of positional updating information related to a new course; therefore, six question marks are used as the position holders for those parameters.
D.A new CallableStatement instance is created by calling the prepareCall() method that is defined in the Connection class.
7.6 Perform Data Manipulations Using Callable Statements 535
private void cmdUpdateActionPerformed(java.awt.event.ActionEvent evt) {
Aif (ComboMethod.getSelectedItem()=="Java Callable Method"){
BCallableStatement cstmt = null; try{
CString query = "{call dbo.UpdateCourse(?, ?, ?, ?, ?, ?)}";
Dcstmt = LogInFrame.con.prepareCall(query);
Ecstmt.setString(1, CourseList.getSelectedValue().toString()); cstmt.setString(2, CourseField.getText()); cstmt.setString(3, ScheduleField.getText()); cstmt.setString(4, ClassroomField.getText());
cstmt.setFloat(5, java.lang.Float.valueOf(CreditField.getText())); cstmt.setInt(6, java.lang.Integer.parseInt(EnrollField.getText()));
Fcstmt.execute();
}
G catch (SQLException e){
msgDlg.setMessage("Error in CallableStatement! " + e.getMessage()); msgDlg.setVisible(true);
}
}
H CourseIDField.setText(CourseList.getSelectedValue().toString());
}
Figure 7.61. The codes for the Update button click event handler.
E.The dynamic query string is initialized with six positional parameters, and the values of those parameters are entered by the user into the associated course-related text fields. The point to be noted is the last two parameters, which are credits (float) and enrollment (integer), respectively. Therefore, the associated setXXX() methods need to be used to initialize these two parameters. Since the Float and Integer classes belong to the java. lang package, here, a full name is used for these classes.
F.The CallableStatement instance is executed to call the stored procedure we built in the last section to update 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 updating process.
H.Finally, the selected course_id from the CourseList listbox is assigned to the Course ID field to indicate this updated course.
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 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 enter the following data into six text fields as an updated course record for the selected course CSE-549:
Course: |
Intelligent Controls |
Schedule: M-W-F: 11:00–11:50 am
