java程式或類可以被儲存到資料庫中,作為PL/SQL的替換或補充。Java可以被用來作為資料庫的觸發器、預存程序、函數、對象的成員函數。在按照下面的過程開發完java預存程序後,就可以從SQL或PL/SQL中調用JAVA預存程序,就像調用普通的PL/SQL過程一樣。下面的代碼描述了如何在SQL*PLUS中開發和使用一個 輸出"Hello, World" 的JAVA程式的例子:
1. Write the Java program using a Java development environment like Jdeveloper or JBuilder.
2. Load the Java program into Oracle8i using either the create or replace
java source command, or with the LOADJAVA utility.
3. Publish your Java procedure to SQL. This step identifies your Java
procedure to SQL and PL/SQL by exposing the procedure entry point,
mapping datatypes in Java to PL/SQL or SQL, and indicating
parameter-passing between Java and PL/SQL or SQL.
(1)編寫java程式
---可以直接在SQL*PLUS中建立JAVA的源檔案,當然如果有已經編譯好的java class,則可以直接跳過這一步,直接到將java程式發布出去這一步
SQL> -- first, create the Java source code
SQL> create or replace java source named "Hello" as
public class Hello {
static public String Message(String name) {
return "Hello, " + name;
}
}
/
Java created.
(2)發布java程式
SQL> -- Now, publish it to SQL
SQL> create or replace function hello (name VARCHAR2) return VARCHAR2
as language java name
'Hello.Message (java.lang.String) return java.lang.String';
Function created.
(3)使用發布的JAVA程式
SQL> -- Now, you can use the Java procedure from a SQL statement
SQL> select hello('world!') from dual;
HELLO('world!')
---------------
Hello world!
--- hello函數在8i中不支援中文,9i中支援。如:
SQL> select hello('你好!') from dual;
HELLO('你好!')
------------------
Hello, 你好!