Tài liệu Teach Yourself PL/SQL in 21 Days- P13 ppt

50 416 0
Tài liệu Teach Yourself PL/SQL in 21 Days- P13 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

PL/SQL and Java 577 20 L ISTING 20.11 Publishing a Java Method with an OUT Argument 1: CREATE OR REPLACE PROCEDURE get_super_name2 ( 2: emp_id IN NUMBER, 3: emp_name OUT VARCHAR2) 4: AS LANGUAGE JAVA 5: NAME ‘Employee2.getSuperName(int, java.lang.String[])’; 6: / In line 3 the emp_name argument is declared as an OUT argument. If you look at the last part of line 5, you’ll see that the corresponding method parameter is an array. Oracle looks at this situation and assumes that element 0 (the first element) of that array is going to contain the output value. When you call this procedure, after the Java method completes, Oracle takes element 0 of the String array, and places it into the variable used for the emp_name parameter. Note that because the Java method has a void return type, it was published as a procedure (line 1) and not as a function. Listing 20.12 shows the get_super_name2 procedure, which you just published in Listing 20.11, being executed from SQL*Plus. L ISTING 20.12 Invoking get_super_name2 from SQL*Plus 1: SQL> VARIABLE emp_id NUMBER 2: SQL> VARIABLE emp_name VARCHAR2(30) 3: SQL> EXECUTE :emp_id := 514; 4: 5: PL/SQL procedure successfully completed. 6: 7: SQL> EXECUTE get_super_name2(:emp_id,:emp_name); 8: 9: PL/SQL procedure successfully completed. 10: 11: SQL> PRINT emp_id 12: 13: EMP_ID 14: --------- 15: 514 16: 17: SQL> PRINT emp_name 18: 19: EMP_NAME 20: -------------------------------- 21: Ashley Nue I NPUT A NALYSIS I NPUT / O UTPUT 26 7982 ch 20 11/30/99 1:30 PM Page 577 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The statements in lines 1 and 2 declare two SQL*Plus bind variables for use when calling the published function. A bind variable is necessary for the output variable because you need a place for PL/SQL to store the output. The EXECUTE state- ment in line 3 sets the value of the emp_id bind variable to 514 . This is the input to the Java method. The EXECUTE statement in line 7 calls the Java method by using the inter- face published in Listing 20.11. Lines 11–15 show the value of the emp_id variable being displayed. It’s still unchanged, at 514 . Lines 17–21 show the contents of the emp_name variable being displayed, which you can see now contains the supervisor’s name. Calling PL/SQL from Java Using SQLJ Just as you can call Java methods from PL/SQL, you can also call PL/SQL procedures and functions from Java. An easy way to do that is by using SQLJ, which is a precompil- er that converts SQL statements, PL/SQL blocks, and the like into a series of JDBC method calls. You’ve already seen SQLJ at work in some of the earlier listings in this chapter. For example, it is used in Listing 20.7 to code the SELECT statement required to retrieve the name of an employee’s supervisor. Using SQLJ to Execute an Anonymous PL/SQL Block As far as SQLJ is concerned, a PL/SQL block is just like an SQL statement—it needs to be sent to the database and executed. You can use SQLJ to execute an anonymous PL/SQL block using the syntax shown here. SQL# { [DECLARE declarations] BEGIN code [EXCEPTION] exception_handlers END } The contents of the curly braces must be a PL/SQL anonymous block, just like the ones that you have been using throughout this book. The parameters above have the following meanings: • declarations refers to any PL/SQL variable definitions that you need in your PL/SQL block. • code refers to the PL/SQL code in the block that you are executing. • exception_handlers refers to any exception handlers (WHEN statements) in the PL/SQL block. The syntax for each of these elements is exactly what you have been learning throughout this book. 578 Day 20 A NALYSIS , S YNTAX , 26 7982 ch 20 11/30/99 1:30 PM Page 578 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. PL/SQL and Java 579 20 You can refer to Java variables within the block by prefacing their variable names with colons. Listing 20.13 shows a relatively simple example of a Java method using SQLJ to call a PL/SQL function. Notice the use of a colon to identify the variable named timeNow as a Java variable. You can find this listing in the file CallAnon.sqlj, which you can download from Macmillan’s Web site for this book. Note L ISTING 20.13 Executing a PL/SQL Block from Java 1: import sqlj.runtime.*; 2: import sqlj.runtime.ref.*; 3: 4: public class CallAnon { 5: 6: public static java.sql.Timestamp getSysdate() throws Exception { 7: 8: java.sql.Timestamp timeNow; 9: 10: #sql { BEGIN 11: :timeNow := sysdate; 12: END 13: }; 14: 15: return timeNow; 16: } 17: } The two imports in lines 1 and 2 are necessary whenever you are using SQLJ. The class name in this example is CallAnon (line 4), and the only method is getSysdate (line 6). The PL/SQL block in lines 10–13 makes a call to Oracle’s built-in SYSDATE function to get the date and time. That value is then stored in the timeNow vari- able, which is a Java variable. The value is finally returned to the method caller in line 15. Using SQLJ to Call a PL/SQL Procedure or Function To call a PL/SQL procedure or function from within Java, you can use the SQLJ CALL statement. There are two slightly different forms of CALL : one for calling procedures and one for calling functions. I NPUT A NALYSIS 26 7982 ch 20 11/30/99 1:30 PM Page 579 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. sql# {CALL procedure_name ( {:in|:out|:inout} param[, {:in|:out|:inout} param .] }; sql# {VALUES (function_name ( {:in|:out|:inout} param[, {:in|:out|:inout} param .] )}; In this syntax the parameters are as follows: • procedure_name is the name of the PL/SQL procedure you want to call. • function_name is the name of the PL/SQL function you want to call. • param is a Java variable. • :in indicates that the parameter is an input parameter. This is the default, and :in can be omitted. • :out indicates that the parameter is an output parameter. • :inout indicates that the parameter is both an input and an output. As an example of calling PL/SQL from Java, you are going to see a slightly modified version of the Employee class shown earlier in Listing 20.7. This version is named Employeeb , and makes use of the PL/SQL function to retrieve the name for any given employee number. This function is named EMPNAME , and is shown in Listing 20.14. L ISTING 20.14 The PL/SQL EMPNAME Function 1: CREATE OR REPLACE FUNCTION empname(empid IN NUMBER) 2: RETURN VARCHAR2 AS 3: empname VARCHAR2(30); 4: BEGIN 5: SELECT emp_name INTO empname 6: FROM employee 7: WHERE emp_id = empid; 8: 9: return empname; 10: EXCEPTION 11: WHEN OTHERS THEN 12: return ‘No name found’; 13: END; 14: / This is really a simple function. It takes one argument, an employee ID number, and retrieves that employee’s name from the database. The SELECT statement is contained in lines 5–7. Line 9 returns the name, if one is found. If any type of error occurs, the assumption is that the employee number was not valid. Line 12 in the excep- tion handling section returns a message to that effect. 580 Day 20 , S YNTAX , I NPUT A NALYSIS 26 7982 ch 20 11/30/99 1:30 PM Page 580 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. PL/SQL and Java 581 20 Listing 20.15 shows the Employeeb class. The getSuperName method has been modified to use the PL/SQL EMPNAME function to retrieve the supervisor’s name. You can find this listing in the file Employeeb.sqlj. You can download this file from the Web site for this book. Note L ISTING 20.15 The Employeeb Class 1: import sqlj.runtime.*; 2: import sqlj.runtime.ref.*; 3: 4: #sql iterator EmpSuper (int superID); 5: 6: public class Employeeb { 7: 8: public static String getSuperName(int empID) throws Exception { 9: 10: /* Declare an iterator (cursor) to return 11: the results of the query to get the supervisor */ 12: EmpSuper iterEmpSuper; 13: 14: /* SELECT the name of the employee’s supervisor */ 15: int empIDb; 16: empIDb = empID; 17: 18: #sql iterEmpSuper={ SELECT supervised_by AS superID 19: FROM employee 20: WHERE emp_id = :empIDb }; 21: 22: /* Return the supervisor’s name to the caller */ 23: if (iterEmpSuper.next()) 24: { 25: java.lang.String superName; 26: int superID; 27: superID = iterEmpSuper.superID(); 28: #sql superName = {VALUES(empname(:superID))}; 29: return superName; 30: } 31: else 32: { 33: return “None”; 34: } 35: } 36: } I NPUT 26 7982 ch 20 11/30/99 1:30 PM Page 581 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The getSuperName method here is only a bit different from that shown in Listing 20.7. There’s still a SELECT statement (lines 18–20), but this time it gets only the supervisor’s ID number, not the supervisor’s name. That ID number is then passed as a parameter to the PL/SQL EMPNAME function (line 28). The PL/SQL function returns the supervisor’s name to the Java method, which in turn returns the value to its caller in line 29. To test this, you can publish the Employeeb.getSuperName method to PL/SQL, and call the method from SQL*Plus. Listing 20.16 does both. L ISTING 20.16 Testing the Employeeb.getSuperName Method 1: CREATE OR REPLACE FUNCTION get_super_nameb ( 2: emp_id IN NUMBER ) 3: RETURN VARCHAR2 4: AS LANGUAGE JAVA 5: NAME ‘Employeeb.getSuperName(int) return java.lang.String’; 6: / Function created. 1: SELECT get_super_nameb(514) 2: FROM dual; GET_SUPER_NAMEB(514) ---------------------------------------------------------------------- Ashley Nue The CREATE OR REPLACE FUNCTION statement in the first part of this listing pub- lishes the Employeeb.getSuperName method. The following SELECT statement uses this method to return the name of employee 514’s supervisor. You end up with a SQL statement calling a published Java method, which then calls a PL/SQL function, which in turn executes a SQL statement. Summary In today’s lesson you have learned how PL/SQL and Java interoperate. You’ve seen how to publish Java methods so that they can be called from PL/SQL, and you’ve seen how to use SQLJ to call PL/SQL methods from Java. You’ve probably even picked up a sense of how SQLJ operates from reading the listings in this lesson. SQLJ is just one of the tools you can use to interact with an Oracle database from Java. JDBC is another option—in fact, SQLJ is translated to JDBC, as is CORBA. 582 Day 20 A NALYSIS I NPUT / O UTPUT A NALYSIS 26 7982 ch 20 11/30/99 1:30 PM Page 582 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. PL/SQL and Java 583 20 Q&A QNow that Java is available in the database, will PL/SQL go away? A Oracle maintains that the answer to this question is no. I tend to agree that PL/SQL is likely to be around for years in the future. Ultimately, though, the marketplace will decide whether there is room for both PL/SQL and Java. Q What is SQLJ? How does it compare to JDBC? A SQLJ is a precompiler. It translates SQL statements and PL/SQL blocks into JDBC method calls. Precompilers have been around for years, and there’s really no differ- ence between what SQLJ does and what PRO*C or PRO*COBOL do. Q When you publish a Java method, does the PL/SQL name need to match the Java name? A No. Because the PL/SQL and Java naming rules are different, that probably couldn’t be the case anyway. For example, Java names are case-sensitive, and PL/SQL names are not. In Java, getSuperName , GETSUPERNAME , and getsupername are all different names. In PL/SQL, they are the same. Q What does it mean to publish a method? A Normally, Java methods are not visible from the PL/SQL world. When you publish a method, you give it a PL/SQL-compatible interface and you make it visible to PL/SQL code. Q When working with Java, is it necessary for the filename to match the name of the class defined within the file? A Generally, yes. Both names are case-sensitive and must match exactly. QI want to drop a class from my database. Should I really use dropjava ? Won’t it delete my source file, too? A No, the dropjava command will not delete any disk files. It reads files, figures out what classes they define, and removes those classes from the database. Workshop You can use this to test your comprehension of this lesson and put what you’ve learned into practice. You’ll find the answers to the quiz and exercises in Appendix A, “Answers.” 26 7982 ch 20 11/30/99 1:30 PM Page 583 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Quiz 1. What does Oracle use for the collective Java capabilities of Orcale8i? 2. What is the name of Oracle’s Java engine? 3. What command-line utility can you use to load Java source code, SQLJ source code, and Java classes into an Oracle8i database? 4. When publishing a Java method, what determines whether you should publish it as a procedure or as a function? Exercise Revisit the Employee class shown in Listing 20.7, and create a PL/SQL function that publishes the getSuperName method. This time, though, make that PL/SQL function part of a package. 584 Day 20 26 7982 ch 20 11/30/99 1:30 PM Page 584 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. D AY 21 W EEK 3 Advanced Queuing by Jonathan Gennick Advanced Queuing (AQ) is a relatively new PL/SQL feature. First introduced with Oracle8, it has been significantly enhanced for Oracle8i. Advanced Queuing is a message-oriented subsystem that provides a robust and reliable way to communicate between applications, even if those applications run on different databases. Although you can’t learn everything there is to know about AQ in one day, you can learn the fundamentals. Today you will learn how to do the following: • Enable AQ on a database •Create a queue • Post messages to the queue • Retrieve messages from a queue 27 7982 ch21 11/30/99 1:29 PM Page 585 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. What Is AQ? Advanced Queuing,or AQ, as it is often called, is a messaging system. Rather than trans- mit messages from one application to another as DBMS_PIPE allows you to do, AQ uses message queues as the basis for message transmission. Processes that generate messages are termed producers. Processes that receive messages are termed consumers. Queues hold the messages between the time that they are posted by a producer and the time that they are received by a consumer. Figure 21.1 illustrates this process. 586 Day 21 F IGURE 21.1 AQ relies on queues for the transmission of messages. Consumer Queue Queue Queue Table Producer Producer Producer Consumer As you can see from Figure 21.1, more than one producer can write messages to a queue, and more than one consumer can receive those messages. AQ’s features are exposed to PL/SQL through two packages. One package, DBMS_AQADM , is used for administrative tasks such as creating queue tables, creating queues, granting access to queues, scheduling propagation, and so forth. The operational interface is con- tained in the DBMS_AQ package, and contains entry points allowing you to send and receive messages. To use AQ as described in this chapter, you need to have Oracle8i Enterprise Edition with the Objects option. Note Removing Some of the Mystery from AQ Oracle has built up a whole new terminology around the subject of advanced queuing. It’s a bit intimidating when you first encounter all those new terms. Table 21.1 defines some of the terms that you will encounter, and attempts to explain them in clear English. 27 7982 ch21 11/30/99 1:29 PM Page 586 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... in the DBMS_AQADM package looks like this: PROCEDURE create_queue_table ( queue_table IN VARCHAR2, queue_payload_TYPE IN VARCHAR2, storage_clause IN VARCHAR2 DEFAULT NULL, sort_list IN VARCHAR2 DEFAULT NULL, multiple_consumers IN BOOLEAN DEFAULT FALSE, message_grouping IN BINARY_INTEGER DEFAULT none, comment IN VARCHAR2 DEFAULT NULL, auto_commit IN BOOLEAN DEFAULT TRUE, primary_instance IN BINARY_INTEGER... secondary_instance IN BINARY_INTEGER DEFAULT 0, compatible IN VARCHAR2 DEFAULT NULL ); 593 , Advanced Queuing Parameters with default values, identified by the keyword DEFAULT, are optional Note In this syntax the parameters are as follows: • QUEUE_TABLE • QUEUE_PAYLOAD • is a text string containing any of the following standard CREATE clauses: STORAGE, INITRANS, MAXTRANS, TABLESPACE, and LOB This string... RECORD ( priority BINARY_INTEGER DEFAULT 1, delay BINARY_INTEGER DEFAULT no_delay, expiration BINARY_INTEGER DEFAULT never, correlation VARCHAR2(128) DEFAULT NULL, attempts BINARY_INTEGER, recipient_list aq$_recipient_list_t, exception_queue VARCHAR2(51) DEFAULT NULL, enqueue_time DATE, state BINARY_INTEGER, sender_id aq$_agent DEFAULT NULL, original_msgid RAW(16) DEFAULT NULL ); In this definition the record... TRUE, is used for the other parameters The queue is started, and both enqueuing and dequeuing are enabled Placing Messages in a Queue After creating and starting a queue, you place messages in the queue by enqueuing them Enqueuing a message involves these steps: 1 Instantiate (that is, create) an object of the payload type 2 Instantiate objects for the enqueue options object, and the message properties... Listing 21. 2 shows how you would call DBMS_AQADM.CREATE_QUEUE_TABLE to create a queue named EMP_CHANGES The payload type is EMP_CHG, the same type created earlier, in Listing 21. 1, and the queue table is defined to support multiple consumers The compatible parameter is set to 8.1 in order to make this an Oracle 8.1-compatible queue table INPUT LISTING 21. 2 Creating the EMP_CHANGES Queue Table 1: BEGIN... messages jump to the front of the line to be retrieved first Messages of equal priority are retrieved in the order in which they were enqueued Line 7 specifies TRUE for the MULTIPLE_CONSUMERS parameter, making this a multipleconsumer queue table No transactional grouping is needed, hence the DBMS_AQADM.NONE in line 8 The text supplied in line 9 is commentary, and shows up in the DBA_QUEUE_TABLES data dictionary... to the queue, while allowing the queue’s consumers to finish out what was already there The code in Listing 21. 4 starts the EMP_DEPT_CHANGES queue that you just created INPUT LISTING 21. 4 Starting the EMP_DEPT_CHANGES Queue 1: BEGIN 2: DBMS_AQADM.START_QUEUE(‘EMP_DEPT_CHANGES’); 3: END; 4: / ANALYSIS The call to DBMS_AQADM.START_QUEUE, shown in line 2, specifies only the queue name Therefore, the default... role AQ_ADMINISTRATOR_ROLE by default Defining a Type for the Payload You define the payload for a message in terms of an Oracle8i object type You define that object type by using the CREATE TYPE command that you learned about on Day 12, “Using Oracle8i Objects for Object-Oriented Programming.” You need to create the type first, because it’s used when creating the queue table Because we are dealing with... The examples in the rest of this lesson take you through the following steps to implement this scenario: 1 Creating a message queue 2 Starting a message queue 3 Placing messages into a queue 4 Retrieving messages from a queue Advanced Queuing FIGURE 21. 2 Pay rate change messages An AQ solution for department and salary changes Payroll Maintenance App Department change messages Employee Maintenance App... Oracle AQ is a robust, secure, and reliable messaging mechanism If you’re thinking of implementing an application using DBMS_PIPE or DBMS_ALERT, consider using AQ instead Q&A Q Can you give me a short, bottom-line description of AQ? A Yes Oracle AQ is a messaging system It’s reliable, it’s robust, and it participates fully in database transactions Using AQ, you can send messages between applications . auto_commit IN BOOLEAN DEFAULT TRUE, primary_instance IN BINARY_INTEGER DEFAULT 0, secondary_instance IN BINARY_INTEGER DEFAULT 0, compatible IN VARCHAR2. ( { :in| :out|:inout} param[, { :in| :out|:inout} param .] }; sql# {VALUES (function_name ( { :in| :out|:inout} param[, { :in| :out|:inout} param .] )}; In this

Ngày đăng: 24/12/2013, 12:17

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan