Table of Contents
一、手动编写Java存储过程/函数
二、使用外部class文件装载创建
三、使用loadjava命令远程装载并创建
Home Database Mysql Tutorial 在Oracle中调用Java Source 的方法

在Oracle中调用Java Source 的方法

Jun 07, 2016 pm 03:51 PM
java oracle source method transfer

通常有三种方法来创建java存储过程。 一、手动编写Java存储过程/函数 利用SQL脚本代码,手动编写可供Oracle调用的Java存储过程或函数,和普通的存储过程/函数创建方法类,以存储过程为例,语法如下: CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED java_

通常有三种方法来创建java存储过程。

一、手动编写Java存储过程/函数

利用SQL脚本代码,手动编写可供Oracle调用的Java存储过程或函数,和普通的存储过程/函数创建方法类似,以存储过程为例,语法如下:

CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED java_soure_name 

AS

示例:创建一个简单的Hello World输出过程,调用JavaSource实现

  1. 创建Java Source

CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED OracleJavaProc
AS
public class OracleJavaProc
{
  public static void main(String[] args) 
	{
		System.out.println("Hello World!");
	}
}
Copy after login

2.  创建存储过程 ,调用Java Source

CREATE OR REPLACE PROCEDURE testoraclejava
AS
LANGUAGE JAVA
NAME 'OracleJavaProc.main(java.lang.String [])';
Copy after login

3.  调用存储过程

begin
  dbms_java.set_output(2000); ---设置Java输出缓冲区大小,否则无法输出数据
  testoraclejava;             ---调用存储过程
end;
Copy after login
输出结果:Hello World!

二、使用外部class文件装载创建

将外部编译好的Java类文件(*.class)通过命令导入到数据库服务器中,实现Java存储过程的创建。

  1. 首先,既然要外部文件导入,那么就需要建立一个目录来存放*.class文件
  2. 其次,将编译好的class文件导入到服务器中
  3. 创建存储过程,调用导入的Java Source

创建目录和Java Source

SQL> create or   replace   directory   test_dir   as  'd:/oracle';  
 
目录已创建。  
 
SQL> create or replace java class using bfile(test_dir, 'OracleJavaProc.class')  
  2  /  
 
Java 已创建。 
Copy after login

TIPS:如果第二步时出现:ORA-29516: Aurora 断言失败: Assertion failure at eox.c:359
Uncaught exception System error:   java/lang/UnsupportedClassVersionError 的错误,机器装了多个Java版本,oracle的Java版本低于环境变量设置的版本。

解决办法:用$ORACLE_HOME/jdk/bin/javac 重新编译java文件。

三、使用loadjava命令远程装载并创建

  • 先创建一个类:

import java.sql.*;  
import oracle.jdbc.*;  
 
public class OracleJavaProc {  
   //Insert a record to the database.  
   public static void insertRecord(int id, String name, int age ,String xman_id) {  
      System.out.println("Inserting new records for EMP...");  
      try 
	  {
		  Connection conn = DriverManager.getConnection("jdbc:default:connection:");  
          String sql = "INSERT INTO emp " +  
					   "(ID,NAME,SALARY,XMAN_ID) " +  
					   "VALUES(?,?,?,?)";
		  PreparedStatement pstmt = conn.prepareStatement(sql);  
		  pstmt.setInt(1,id);
		  pstmt.setString(2,name);
		  pstmt.setInt(3,age);
		  pstmt.setString(4,xman_id);
		  pstmt.executeUpdate();  
		  pstmt.close();
	  } 
	  catch(SQLException e) 
	  {
		  System.err.println("ERROR! Inserting record: " + e.getMessage());
	  }  
   }
   //Select a reords from database
   public static boolean recordQuery(int id) {
	   System.out.println("Querying records from EMP...");
	   try
	   {
		   Connection conn = DriverManager.getConnection("jdbc:default:connection:");
		   String sql = "SELECT * FROM emp WHERE id = ?";
		   PreparedStatement pstmt = conn.prepareStatement(sql);
		   pstmt.setInt(1,id);
		   ResultSet rs = pstmt.executeQuery();

		   while(rs.next()) {
			   System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
								  rs.getInt(3)+"\t"+rs.getString(4));
		   }
		   return true;
	   }
	   catch (SQLException e)
	   {
		   System.err.println("ERROR! Querying record: " + e.getMessage());
		   return false;
	   }
   }
} 
Copy after login
  • 使用loadjava命令将其装载到服务器端并编译:

D:\Oracle>loadjava -u hbi/hbi@orcl -v -resolve OracleJavaProc.java

arguments: '-u' 'hbi/hbi@orcl' '-v' '-resolve' 'OracleJavaProc.java'

creating : source OracleJavaProc

loading  : source OracleJavaProc

resolving: source OracleJavaProc

Classes Loaded: 0

Resources Loaded: 0

Sources Loaded: 1

Published Interfaces: 0

Classes generated: 0

Classes skipped: 0

Synonyms Created: 0

Errors: 0

  • 创建存储过程和函数:

创建存储过程,实现数据插入:

create or replace procedure INSERT_RECORD(V_ID      number,
                                          V_NAME    varchar2,
                                          V_SALARY  number,
                                          V_XMAN_ID varchar2) as
language java name 'OracleJavaProc.insertRecord(int,java.lang.String,int,java.lang.String)';
Copy after login
创建函数,实现数据查询:

create or replace function QUERY_TABLE(v_id number) return number 
as
  language java name 'OracleJavaProc.recordQuery(int) return int';
Copy after login
  • 测试一下结果:

SQL> set serveroutput on size 2000  
SQL> call dbms_java.set_output(2000);  
 
调用完成。  
 
SQL> execute add_salgrade(29, 'Charles', 5000, '029');  
Inserting new records for EMP...
 
PL/SQL 过程已成功完成。
Copy after login

  在Oracle中调用Java Source 的方法

  • 更新你已经编写的Java存储过程

修改好Java源代码后,先dropjava ,再loadjava。

D:\Oracle>dropjava -u hbi/hbi@orcl -v OracleJavaProc
dropping: source OracleJavaProc

D:\Oracle>loadjava -u hbi/hbi@orcl -v -resolve OracleJavaProc.java
arguments: '-u' 'hbi/hbi@orcl' '-v' '-resolve' 'OracleJavaProc.java'
creating : source OracleJavaProc
loading  : source OracleJavaProc
resolving: source OracleJavaProc
Classes Loaded: 0
Resources Loaded: 0
Sources Loaded: 1
Published Interfaces: 0
Classes generated: 0
Classes skipped: 0
Synonyms Created: 0
Errors: 0


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to encrypt oracle view How to encrypt oracle view Apr 11, 2025 pm 08:30 PM

Oracle View Encryption allows you to encrypt data in the view, thereby enhancing the security of sensitive information. The steps include: 1) creating the master encryption key (MEk); 2) creating an encrypted view, specifying the view and MEk to be encrypted; 3) authorizing users to access the encrypted view. How encrypted views work: When a user querys for an encrypted view, Oracle uses MEk to decrypt data, ensuring that only authorized users can access readable data.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

How to solve the problem of closing oracle cursor How to solve the problem of closing oracle cursor Apr 11, 2025 pm 10:18 PM

The method to solve the Oracle cursor closure problem includes: explicitly closing the cursor using the CLOSE statement. Declare the cursor in the FOR UPDATE clause so that it automatically closes after the scope is ended. Declare the cursor in the USING clause so that it automatically closes when the associated PL/SQL variable is closed. Use exception handling to ensure that the cursor is closed in any exception situation. Use the connection pool to automatically close the cursor. Disable automatic submission and delay cursor closing.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How to delete all data from oracle How to delete all data from oracle Apr 11, 2025 pm 08:36 PM

Deleting all data in Oracle requires the following steps: 1. Establish a connection; 2. Disable foreign key constraints; 3. Delete table data; 4. Submit transactions; 5. Enable foreign key constraints (optional). Be sure to back up the database before execution to prevent data loss.

How to create oracle dynamic sql How to create oracle dynamic sql Apr 12, 2025 am 06:06 AM

SQL statements can be created and executed based on runtime input by using Oracle's dynamic SQL. The steps include: preparing an empty string variable to store dynamically generated SQL statements. Use the EXECUTE IMMEDIATE or PREPARE statement to compile and execute dynamic SQL statements. Use bind variable to pass user input or other dynamic values ​​to dynamic SQL. Use EXECUTE IMMEDIATE or EXECUTE to execute dynamic SQL statements.

How to create cursors in oracle loop How to create cursors in oracle loop Apr 12, 2025 am 06:18 AM

In Oracle, the FOR LOOP loop can create cursors dynamically. The steps are: 1. Define the cursor type; 2. Create the loop; 3. Create the cursor dynamically; 4. Execute the cursor; 5. Close the cursor. Example: A cursor can be created cycle-by-circuit to display the names and salaries of the top 10 employees.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles