Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
788
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

546 Chapter 7 Insert, Update, and Delete Data from Databases

UPDATE Course

SET course = inCourse, credit = inCredit, classroom = inClassroom,

Schedule = inSchedule, enrollment = inEnroll

WHERE course_id = CourseID;

Figure 7.73. The body of the stored procedure.

Figure 7.74. The finished UpdateCourse stored procedure.

Your finished Procedure-Define page is shown in Figure 7.74.

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 last stored procedure DeleteCourse().

7.6.2.2.3 Create the DeleteCourse Stored Procedure Click on the Create button located at the upper-right corner of this UpdateCourse() procedure window and select the Procedure to open a new procedure page.

Enter DeleteCourse into the Procedure Name field and keep the Include Arguments checkbox checked, then click on the Next button.

In the Arguments page, enter a CourseID for which the associated course will be deleted into the first Argument field. Refer to Section 2.11.2.3 in Chapter 2 to get this data type. Your finished Arguments page should match one that is shown in Figure 7.75.

Click on the Next button to go to the procedure-defining page.

Enter the codes that are shown in Figure 7.76 into this new procedure as the body of this procedure using the PL-SQL language. 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.77.

7.6 Perform Data Manipulations Using Callable Statements 547

Figure 7.75. The finished Arguments page.

DELETE FROM Course WHERE course_id = CourseID;

Figure 7.76. The body of the stored procedure.

Figure 7.77. The finished stored procedure DeleteCourse().

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.

At this point, we have finished building all three stored procedures in the Oracle database environment. Now close the Oracle Database 10g XE, and we can test the codes we made in Section 7.6.2.1 to call them to perform the associated data actions.

7.6.2.3 Build and Run the Project to Test the Data Manipulations

Launch NetBeans IDE 6.8 and our project OracleSelectObject. Click on the Clean and Build Main Project button to build the project. Then click on the Run Main Project button to run the project.

548 Chapter 7 Insert, Update, and Delete Data from Databases

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.78, and you can see that the new inserted course CSE-549 is indeed added to the database and displayed in the CourseList listbox.

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 a.m.

Figure 7.78. The running result for calling the InsertNewCourse() stored procedure.

7.6 Perform Data Manipulations Using Callable Statements 549

Figure 7.79. The running result for calling the UpdateCourse() stored procedure.

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.79.

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 Oracle database by right clicking on that URL and select the Connect item.Then expand that connected URL and our CSE_DEPT database node 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.80.

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 to Oracle database using CallableStatement object method. A complete project OracleSelectObject that contains all three data manipulation actions to the Oracle

550 Chapter 7 Insert, Update, and Delete Data from Databases

Figure 7.80. The updated course CSE-549.

database can be found at the folder DBProjects\Chapter 7, which is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).

7.7 CHAPTER SUMMARY

Three popular data manipulations against two kinds of databases, SQL Server and Oracle, have been discussed and analyzed in detailed with quite a few real project examples in this chapter.

This chapter is divided into two parts: Insert, update, and delete data to our sample database using JPA wizards, and insert, update, and delete data using the Java runtime object method. Relatively, the second method provides more flexibility and efficiency in data actions against different databases. In the second part, two more data manipulation methods, Updatable ResultSet and CallableStatement, are discussed with real projects for two popular databases, SQL Server and Oracle.

Detailed introduction and illustrations on building stored procedures under different database systems are provided with real and step-by-step examples. After finished this chapter, readers will be

Able to design and build professional data actions against popular database systems using the JPA wizards.

Able to design and build professional data actions against popular database systems using the Java runtime objects.

Able to design and build popular stored procedures for different database systems.

Homwork 551

Able to design and build professional data actions against popular databases using Updatable ResultSet methods.

Able to design and build professional data actions against popular databases using CallableStatement methods.

Starting from next chapter, we will discuss the Java Web database programming.

HOMEWORK

I. True/False Selections

____1. To use JPA to perform data manipulations against target databases, one needs first to set up a connection to the target database using JPA wizard.

____2. A persistence unit is used to hold a set of entities that can be managed by a given EntityManager instance.

____3. The persist() method, which belongs to the persistence unit, is used to add all necessary entities into the persistence context that can be managed by the EntityManager.

____4. For all kinds of data query, such as Select, Update, Delete, and even the execution of the persist() method, a Transaction Association must be started to monitor and execute this data query.

____5. In JPQL, no INSERT identifier is defined and implemented because we do not need this kind of identifier to do any mapping between a query string and an object, and we can directly insert a object using the persist() method.

____6. When using JPQL to create a dynamic data manipulation query string, one can only use the positional parameters in that query string.

____7. When using JPQL to perform data manipulations, the Transaction instance must be triggered and started by executing the commit() method.

____8. When perform data manipulations using Java runtime object method, one can use either executeUpdate() or execute() method.

____9. A default ResultSet object is updatable and has a cursor that can move either forward and backward.

___10. To insert a new record into a database using the Updatable ResultSet method, one needs first to move the cursor to an insert-row that is a blank row and is not a part of the ResultSet but related to the ResultSet.

II. Multiple Choices

1.When using JPA wizard to perform data manipulations, in order to create a Transaction Association instance, one need to use the __________ method.

a.begin()

b.getTransaction()

c.persist()

d.commit()

2.When using JPA wizard to perform data manipulations, the following data manipulations, such as ________________, need a Transaction Association instance.

a.Update and Selection

b.Delete and Selection

552 Chapter 7 Insert, Update, and Delete Data from Databases

c.Update, Delete, and Select

d.Update and Delete

3.When using an Updatable ResultSet to perform data manipulations, two parameters can be used to set up properties of a ResultSet object, they are __________________.

a.Forward-only, Updatable

b.Scroll-sensitive, Read-only

c.ResultSet Type, Concurrency Type of a ResultSet

d.ResultSet Type, Updatable Type

4.Which of the following created ResultSet protocol is correct? __________

a.Statement createStatement(int resultSetType, int resultSetConcurrency).

b.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency).

c.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency).

d.All of them.

5.To update a record using the Updatable ResultSet, one needs to use ______ steps and they are:

_________________________.

a.1, UpdateXXX()

b.2, UpdateXXX() and UpdateRow()

c.3, UpdateXXX(), UpdateCursor() and UpdateRow()

d.4, MoveToRow(), UpdateXXX(), UpdateCursor() and UpdateRow()

6.To insert a new record using the Updatable ResultSet, one needs to use ______ steps and they are: _________________________.

a.1, insertRow()

b.2, moveToInsertRow(), insertRow()

c.3, moveToInsertRow(),updateXXX(), insertRow()

d.4, moveToCursor(), moveToInsertRow(), updateXXX(), insertRow()

7.When building an Oracle stored procedure to perform data updating action, one needs to use the ____ input parameters to ______ them with the column names in the query string.

a.Different, distinguish

b.Same, identify

c.Same, distinguish.

d.Different, identify

8.By using which of the following static constant values, we can set an Updatable Result object that has a cursor that can move either forward and backward?

a.ResultSet.TYPE_FORWARD_ONLY

b.ResultSet.TYPE_SCROLL_INSENSITIVE

c.ResultSet.CONCUR_UPDATABLE

d.ResultSet.TYPE_SCROLL_SENSITIVE

9.By using which of the following static constant values can we set an Updatable Result object whose contents can be updated?

a.ResultSet.TYPE_FORWARD_ONLY

b.ResultSet.TYPE_SCROLL_INSENSITIVE

c.ResultSet.CONCUR_UPDATABLE

d.ResultSet.TYPE_SCROLL_SENSITIVE

Homwork 553

10. Every EntityManager has a _________ relation with an EntityTransaction instance. If an applicationrequiresmultipleconcurrenttransactions,onecanuse____________EntityManager(s)

a.one-to-many, one

b.many-to-one, multiple

c.many-to-many, multiple

d.one-to-one, multiple

III. Exercises

1.Provide a brief description about the persist() method in the EntityManager class.

2.Provide a brief discussion about the Transaction Association object.

3.Figure 7.81 shows a piece of codes used to perform a data manipulation in JPA environment. Provide a clear and detailed explanation for each step and list them one by one.

4.List six steps to use Java runtime object to perform data manipulations against our target database.

5.List three steps to insert a new record into a target database using the Updatable ResultSet method. Convert the pseudo-codes shown below to the real Java codes (assume that a valid connection conn has been established).

a.Create an Insert query.

b.Create a PreparedStatement instance with two ResultSet parameters, TYPE_SCROLL_ SENSITIVE and CONCUR_UPDATABLE, to define the ResultSet object to enable it to be scrollable and updatable, and enable it to perform data manipulations.

c.The setString() method is used to initialize the positional parameter in the query string.

d.The executeQuery() method is called to perform this query and return the query result to a newly created ResultSet object.

e.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.

f.Two updateString() methods are executed to insert two desired columns to the associated columns in the ResultSet.

g.The insertRow() method is executed to update this change to the database.

ABook book = new Book("1B78-YU9L", "JavaWorld");

BCompany pub = new Company("Weston House");

Cpub.setRevenue(1750000D);

book.setPublisher(pub);

pub.addBook(mag);

DEntityManager em = emf.createEntityManager();

Eem.getTransaction().begin();

Fem.persist(book);

em.persist(pub);

Gem.getTransaction().commit();

// or we could continue using the EntityManager...

Hem.close();

Figure 7.81. A piece of codes used to insert some data into two tables.

554 Chapter 7 Insert, Update, and Delete Data from Databases

6.Refer to Section 7.3.1 to develop codes for the StudentFrame form window to insert a new student record into the Student table in our sample database using the Java runtime object method. The student’s photo can be the Default.jpg.

7.Refer to Section 7.6.1.2 to develop codes for the FacultyFrame form class to update a faculty record for the Faculty table in our sample SQL Server database using CallableStatement method. The faculty’s photo will be kept unchanged.

PART II

Building Three-Tier

Client–Server Applications