Perform Data Manipulations to SQL Server Database

Một phần của tài liệu practical database aprogramming with java (Trang 398 - 415)

JAVA RUNTIME OBJECTS METHOD

7.6 PERFORM DATA MANIPULATIONS USING CALLABLE STATEMENTS

7.6.1 Perform Data Manipulations to SQL Server Database

Since the similarity between data manipulations for the SQL Server and the Oracle databases, we start with the data manipulations against the SQL Server database. First let ’ s take care of the data insertion to the Course table in our sample SQL Server data- base using the CallableStatement method.

7.6.1.1 Insert Data to SQL Server Database Using Callable Statements

In Section 6.4.1 in Chapter 6 , we have built a project SQLSelectObject with some graphi- cal user interface ( GUI ), including the CourseFrame form window, and we want to use that CourseFrame form window in that project with some modifi cations to make it as our GUI in this section. We will build the data insertion function with the CallableStatement method in the following procedures:

1. Modify the CourseFrame form window by adding one more Course ID text fi eld to enable us to insert a new course record with this new course_id .

2. Build our stored procedure dbo.InsertNewCourse using the SQL Server Management Studio Express.

3. Develop the codes for the Insert button in the CourseFrame form window to execute the CallableStatement method to call our stored procedure dbo.InsertNewCourse to insert this new course record into the Course table in our sample database.

4. Confi rm and validate this new course insertion using the codes we built for the Select button event handler.

Now let ’ s start from the fi rst step.

7.6.1.1.1 Modify the CourseFrame Form Window To save time and space, we want to use and modify a project SQLSelectObject we built in Section 7.3.1 to make it as our new project to perform this data insertion action.

Perform the following operations to make it as our project:

1. Launch NetBeans IDE 6.8 and open the Projects window.

2. Right click on the project SQLSelectObject we built in Section 7.3.1 and select the Set as Main Project item from the pop - up menu. If you cannot fi nd this project, copy this project from the folder DBProjects\Chapter 7 located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1 ) and paste it to your default project folder JavaDBProject\Chapter 7 . Then in the NetBeans IDE, go to File > Open Project menu item to open this project.

3. Double click on the CourseFrame.java to open the CourseFrame class.

4. Click on the Design button to open the CourseFrame form window.

Perform the following modifi cations to this form:

• Add a Label and a Text Field into the Course Information panel with the properties shown in Table 7.15 .

• Add two buttons, Update and Delete, with the properties shown in Table 7.15 . Also, rear- range these fi ve buttons to the bottom of the CourseFrame form.

c07.indd 523

c07.indd 523 7/20/2011 11:12:09 AM7/20/2011 11:12:09 AM

www.traintelco.com

Your fi nished CourseFrame form window should match one that is shown in Figure 7.50 .

Before we can build the project using the CallableStatement method to perform the data manipulations, we need fi rst to develop our stored procedure dbo.InsertNewCourse using the Microsoft SQL Server Management Studio Express.

7.6.1.1.2 Develop the Stored Procedure dbo.InsertNewCourse Recall that when we built our sample database CSE_DEPT in Chapter 2 , there is no faculty name column in the Course table, and the only relationship that exist between the Faculty and the Course tables is the faculty_id , which is a primary key in the Faculty table, but a foreign key in the Course table. As the project runs, the user needs to insert a new course record based on the faculty name, not the faculty ID. Therefore, for this new course data inser- tion, we need to perform two queries with two tables: fi rst, we need to make a query to the Faculty table to get the faculty_id based on the faculty name selected by the user, and second, we can insert a new course record based on the faculty_id we obtained from our fi rst query. These two queries can be combined into a single stored procedure.

Launch the Microsoft SQL Server Management Studio Express by going to Start > All Programs > Microsoft SQL Server 2008 > SQL Server Management Studio . Click

Figure 7.50. The modifi ed CourseFrame form window.

Table 7.15. Objects and controls added into the courseframe window

Type Variable Name Text editable Title

Label Label1 Course ID

Text Field CourseIDField checked

Button cmdUpdate Update

Button cmdDelete Delete

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, and select the New Stored Procedure to open a new stored procedure template, as shown in Figure 7.51 .

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 following codes that are shown in Figure 7.52 into this stored procedure template as the body of our new stored procedure. The newly added codes have been highlighted in bold and indicated in steps A, B, and C, respectively. The codes in green color are comments for this stored procedure.

Go to File > Save SQLQuery1.sql to save this stored procedure.

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 from the Object Explorer window and select the Refresh item to refresh it to get our newly created stored procedure dbo.InsertNewCourse . Right click on our newly stored procedure and select the Execute Stored Procedure to open the Execute Procedure wizard, which is shown in Figure 7.53 .

Figure 7.51. The newly stored procedure template.

c07.indd 525

c07.indd 525 7/20/2011 11:12:09 AM7/20/2011 11:12:09 AM

www.traintelco.com

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 con- tinue to develop the codes for the CallableStatement method to call this stored procedure to perform a new course insertion action against our sample database.

Figure 7.52. The codes for our new stored procedure.

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 -- =============================================

CREATE PROCEDURE dbo.InsertNewCourse -- Add the parameters for the stored procedure here

@FacultyName VARCHAR(50), @CourseID VARCHAR(50), @Course text,

@Schedule text, @Classroom text, @Creditint, @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 DECLARE @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 A B

C

7.6.1.1.3 Develop the Codes for the Insert Button Click Event Handler The func- tion 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 confi rm 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.

Figure 7.53. The opened Execute Procedure wizard.

c07.indd 527

c07.indd 527 7/20/2011 11:12:09 AM7/20/2011 11:12:09 AM

www.traintelco.com

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 infor- mation 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 defi ned 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 fi elds.

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.

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 fi elds 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 confi rm 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.

Figure 7.55. The codes for the Insert button click event handler.

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

if (ComboMethod.getSelectedItem()=="Java Callable Method"){

CallableStatement cstmt = null;

try{

String query = "{call dbo.InsertNewCourse(?, ?, ?, ?, ?, ?, ?)}";

cstmt = LogInFrame.con.prepareCall(query);

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

cstmt.execute();

}

catch (SQLException e){

msgDlg.setMessage("Error in CallableStatement! " + e.getMessage());

msgDlg.setVisible(true);

} } } A

B C D E

F G

c07.indd 529

c07.indd 529 7/20/2011 11:12:09 AM7/20/2011 11:12:09 AM

www.traintelco.com

Another way to confi rm 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 fi nd 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 fi rst 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 fi rst 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.

Figure 7.56. The running result for the data insertion validation.

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

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 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 proce- dure 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 proce- dure 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 fol- lowing 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.

Figure 7.57. The newly inserted new course CSE - 549.

c07.indd 531

c07.indd 531 7/20/2011 11:12:09 AM7/20/2011 11:12:09 AM

www.traintelco.com

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 fi nished 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 high- lighted 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 fi rst 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.

Figure 7.58. The codes for the dbo.UpdateCourse stored procedure.

-- ================================================

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

@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 UPDATE Course

SET course = @Course, schedule = @Schedule, classroom = @Classroom, credit = @Credit, enrollment = @Enroll

WHERE (course_id = @CourseID) END

GO A

B

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

Figure 7.59. The Finished Query Designer wizard.

c07.indd 533

c07.indd 533 7/20/2011 11:12:10 AM7/20/2011 11:12:10 AM

www.traintelco.com

Một phần của tài liệu practical database aprogramming with java (Trang 398 - 415)

Tải bản đầy đủ (PDF)

(791 trang)