在pl/sql中调用shell命令

本文介绍了在Oracle数据库中执行外部命令的三种方法:通过DBMS_PIPE包结合OS上的守护进程、利用Java的getRuntime().exec方法及使用Oracle的EXECUTABLE jobs功能。详细展示了Java方法的具体步骤,并指出了其潜在问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本来想是一个很简单的操作,可惜Oracle没有提供简单的一个命令(也许我不知道吧),只好进行一些复杂点的操作了。一般有三种方式实现:1. 利用DBMS_PIPE包并创建OS上运行的守护进程;2. 利用java的getRuntime().exec;3. 使用oracle的EXECUTABLE jobs功能。

利用DBMS_PIPE包并创建OS上运行的守护进程

    觉得这种方式复杂,还要用到pro*c,没试。这里有个例子

利用java的getRuntime().exec

    这种好点,java用的还是蛮多的。

1)写个简单的java程序 ExecuteCmd.java

import java.lang.Runtime;
import java.lang.Process;
import java.io.IOException;
import java.lang.InterruptedException;

class ExecuteCmd {

    public static void main(String args[]) {

        System.out.println("Start executing");

        try {

            /* Execute the command using the Runtime object and get the
            Process which controls this command */
            Process p = Runtime.getRuntime().exec(args[0]);

            /* Use the following code to wait for the process to finish
            and check the return code from the process */
            try {

                p.waitFor();

            /* Handle exceptions for waitFor() */
            } catch (InterruptedException intexc) {
            System.out.println("Interrupted Exception on waitFor: " + intexc.getMessage());
            }

        System.out.println("Return code from process: "+ p.exitValue());
        System.out.println("Done executing");

        /* Handle the exceptions for exec() */
        } catch (IOException e) {

            System.out.println("IO Exception from exec: " + e.getMessage());
            e.printStackTrace();

        }
    }
}

2)编译生成 ExecuteCmd.class

javac ExecuteCmd.java

3)加载到oracle中

$ loadjava -user system/manager ExecuteCmd.class

4)生成java存储过程

CREATE OR REPLACE PROCEDURE executecmd (S1 VARCHAR2)
    AS LANGUAGE JAVA
    name 'ExecuteCmd.main(java.lang.String[])';
/

测试:

SQL> set serveroutput on 
SQL> call dbms_java.set_output(2000); 
SQL> EXEC executecmd('/bin/touch /home/oracle/a.txt'); 
Start executing 
Return code from process: 0 
Done executing 
PL/SQL procedure successfully completed. 

SQL> host 
$ ls /home/oracle
a.txt 

    执行成功了,但还是有些问题,比如参数中不能使用环境变量 EXEC executecmd('/bin/touch $HOME/a.txt')执行不行,绝对路径和相对路径的问题,还要给执行用户(这里是system用户)授予相应的权限等等。所以我觉得还是应该先把要做的事写一个shell可执行脚本,然后再如上调用,这样会省去一些麻烦。

使用oracle的EXECUTABLE jobs功能

    对DBMS_SCHEDULER没什么研究,论坛上有个例子,但我没试通,有时间再研究一下,应该也可以。

exec DBMS_SCHEDULER.CREATE_JOB(job_name=>'test13',job_type=>'EXECUTABLE',job_action=>'/tmp/test1.sh');
exec DBMS_SCHEDULER.RUN_JOB(job_name=>'test13');

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值