如何在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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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

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.

Solutions to Oracle cannot be opened include: 1. Start the database service; 2. Start the listener; 3. Check port conflicts; 4. Set environment variables correctly; 5. Make sure the firewall or antivirus software does not block the connection; 6. Check whether the server is closed; 7. Use RMAN to recover corrupt files; 8. Check whether the TNS service name is correct; 9. Check network connection; 10. Reinstall Oracle software.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

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.

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.

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 is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
