如何在Oracle中使用Java存储过程 (详解)
其实,这篇短文,我早就应该写了。因为,java存储过程今后在各大数据库厂商中越来越流行,功能也越来越强大。这里以Oracle为例,介绍一下java存储过程的具体用法。 iihero on csdn) 一、如何创建java存储过程? 通常有三种方法来创建java存储过程。 1. 使用o
其实,这篇短文,我早就应该写了。因为,java存储过程今后在各大数据库厂商中越来越流行,功能也越来越强大。这里以Oracle为例,介绍一下java存储过程的具体用法。
iihero on csdn)
一、如何创建java存储过程?
通常有三种方法来创建java存储过程。
1. 使用oracle的sql语句来创建:
e.g. 使用create or replace and compile java source named "
后边跟上java源程序。要求类的方法必须是public static的,才能用于存储过程。
SQL> create or replace and compile java source named "javademo1"
2 as
3 import java.sql.*;
4 public class JavaDemo1
5 {
6 public static void main(String[] argv)
7 {
8 System.out.println("hello, java demo1");
9 }
10 }
11 /
Java 已创建。
SQL> show errors java source "javademo1"
没有错误。
SQL> create or replace procedure javademo1
2 as
3 language java name 'JavaDemo1.main(java.lang.String[])';
4 /
过程已创建。
SQL> set serveroutput on
SQL> call javademo1();
调用完成。
SQL> call dbms_java.set_output(5000);
调用完成。
SQL> call javademo1();
hello, java demo1
调用完成。
SQL> call javademo1();
hello, java demo1
调用完成。
2. 使用外部class文件来装载创建
e.g. 这里既然用到了外部文件,必然要将class文件放到oracle Server的某一目录下边。
public class OracleJavaProc
{
public static void main(String[] argv)
{
System.out.println("It's a Java Oracle procedure.");
}
}
SQL> grant create any directory to scott;
授权成功。
SQL> conn scott/tiger@iihero.oracledb
已连接。
SQL> create or replace directory test_dir as 'd:/oracle';
目录已创建。
SQL> create or replace java class using bfile(test_dir, 'OracleJavaProc.CLASS')
2 /
Java 已创建。
SQL> create or replace procedure testjavaproc as language java name 'OracleJavaProc.main(java.lang.String[])';
2 /
过程已创建。
SQL> call testjavaproc();
调用完成。
SQL> execute testjavaproc;
PL/SQL 过程已成功完成。
SQL> set serveroutput on size 5000
SQL> call dbms_java.set_output(5000);
调用完成。
SQL> execute testjavaproc;
It's a Java Oracle procedure.
3. 我推荐的一种方法,直接使用loadjava命令远程装载并创建。
先创建一个类, e.g.
import java.sql.*;
import oracle.jdbc.*;
public class OracleJavaProc ...{
//Add a salgrade to the database.
public static void addSalGrade(int grade, int losal, int hisal) ...{
System.out.println("Creating new salgrade for EMPLOYEE...");
try ...{
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
String sql =
"INSERT INTO salgrade " +
"(GRADE,LOSAL,HISAL) " +
"VALUES(?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,grade);
pstmt.setInt(2,losal);
pstmt.setInt(3,hisal);
pstmt.executeUpdate();
pstmt.close();
}
catch(SQLException e) ...{
System.err.println("ERROR! Adding Salgrade: "
+ e.getMessage());
}
}
}
使用loadjava命令将其装载到服务器端并编译:
D:eclipse3.1workspacedbtest>loadjava -u scott/tiger@iihero.oracledb -v -resolve Or
acleJavaProc.java
arguments: '-u' 'scott/tiger@iihero.oracledb '-v' '-resolve' 'OracleJavaProc.java'
creating : source OracleJavaProc
loading : source OracleJavaProc
resolving: source OracleJavaProc
查询一下状态:
连接到:
Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production
SQL> SELECT object_name, object_type, status FROM user_objects WHERE object_type LIKE 'JAVA%';
OBJECT_NAME
--------------------------------------------------------------------------------
OBJECT_TYPE STATUS
------------------------------------ --------------
OracleJavaProc
JAVA CLASS VALID
OracleJavaProc
JAVA SOURCE VALID
测试一下存储过程:
SQL> create or replace procedure add_salgrade(id number, losal number, hisal num
ber) as language java name 'OracleJavaProc.addSalGrade(int, int, int)';
2 /
过程已创建。
SQL> set serveroutput on size 2000
SQL> call dbms_java.set_output(2000);
调用完成。
SQL> execute add_salgrade(6, 10000, 15000);
Creating new salgrade for EMPLOYEE...
PL/SQL 过程已成功完成。
SQL> select * from salgrade where grade=6;
GRADE LOSAL HISAL
---------- ---------- ----------
6 10000 15000
二、如何更新你已经编写的java存储过程?
假如要往类OracleJavaProc里添加一个存储过程方法,如何开发?
正确的步骤应该是先dropjava, 改程序,再loadjava。
e.g.修改OracleJavaProc类内容如下:
import java.sql.*;
import oracle.jdbc.*;
public class OracleJavaProc ...{
// Add a salgrade to the database.
public static void addSalGrade(int grade, int losal, int hisal) ...{
System.out.println("Creating new salgrade for EMPLOYEE...");
try ...{
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
String sql =
"INSERT INTO salgrade " +
"(GRADE,LOSAL,HISAL) " +
"VALUES(?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,grade);
pstmt.setInt(2,losal);
pstmt.setInt(3,hisal);
pstmt.executeUpdate();
pstmt.close();
}
catch(SQLException e) ...{
System.err.println("ERROR! Adding Salgrade: "
+ e.getMessage());
}
}
public static int getHiSal(int grade)
...{
try ...{
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
String sql = "SELECT hisal FROM salgrade WHERE grade = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);pstmt.setInt(1, grade);
ResultSet rset = pstmt.executeQuery();
int res = 0;
if (rset.next())
...{
res = rset.getInt(1);
}
rset.close();
return res;
} catch (SQLException e)
...{
System.err.println("ERROR! Querying Salgrade: "
+ e.getMessage());
return -1; }
}
}
如何更新呢?
D:eclipse3.1workspacedbtest>dropjava -u scott -v OracleJavaProc
D:/tiger@iihero.oracledbeclipse3.1workspacedbtest>loadjava -u scott -v -resolve Or
acleJavaProc/tiger@iihero.oracledb.java
arguments: '-u' 'scott/tiger@iihero.oracledb' '-v' '-resolve' 'OracleJavaProc.java'
creating : source OracleJavaProc
loading : source OracleJavaProc
resolving: source OracleJavaProc
后边的应用示例:
SQL> create or replace function query_hisal(grade number) return number as langu
age java name 'OracleJavaProc.getHiSal(int) return int';
2 /
函数已创建。
SQL> set serveroutput on size 2000
SQL> call dbms_java.set_output(2000);
调用完成。
SQL> select query_hisal(5) from dual;
QUERY_HISAL(5)
--------------
9999
全文完!
用法个人见解:不要手动drop java source, 不要手动drop procedure。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4
