技术开发 频道

Oracle执行Java代码

    【IT168 技术文档】需要确认数据库系统已经选择安装了JAVA虚拟机组件

    1、登陆SYS用户,执行以下代码

    begin
    Dbms_Java.Grant_Permission('PSIID','java.io.FilePermission', '<<ALL FILE>>','read ,write, execute, delete');
    Dbms_java.grant_permission('PSIID', 'SYS:java.io.FilePermission', '<<ALL FILES>>','read ,write, execute, delete');
    Dbms_Java.Grant_Permission('PSIID', 'java.io.FilePermission', 'd:a.bat','read ,write, execute, delete');
    dbms_java.grant_permission('PSIID', 'java.lang.RuntimePermission','*','writeFileDescriptor' );
    end;

    2、登陆psiid用户创建java程序资源

    create or replace and compile
    java source named "Util"
    as
    import java.io.*;
    import java.lang.*;
    public class Util extends Object
    {
    public static int RunThis(String args)
    {
    Runtime rt = Runtime.getRuntime();
    int rc = -1;
    try
    {
    Process p = rt.exec(args);
    int bufSize = 4096;
    BufferedInputStream bis =
    new BufferedInputStream(p.getInputStream(), bufSize);
    int len;
    byte buffer[] = new byte[bufSize];
    // Echo back what the program spit out
    while ((len = bis.read(buffer, 0, bufSize)) != -1)
    System.out.write(buffer, 0, len);
    rc = p.waitFor();
    }
    catch (Exception e)
    {
    e.printStackTrace();
    rc = -1;
    }
    finally
    {
    return rc;
    }
    }
    }

    3、创建调用Java资源的函数

    create or replace function RUN_CMD(p_cmd in varchar2) return number
    as
    language java name 'Util.RunThis(java.lang.String) return integer';

    4、建立一过程调用存储过程

    create or replace procedure RUN(p_cmd in varchar2)
    as
    x number;
    begin
    x := run_cmd(p_cmd);
    end;

    ------------------------------
    ------- 执行例子
    ------------------------------
    --d:a.bat 文件
    cd d:
    rename %1 %2

    SQL> exec rc('d:a.bat mytest.sql b.sql') ;
    D:oracleora92DATABASE>cd d:
    D:>rename mytest.sql b.sql

    exec :x := RUN_CMD('ipconfig');

    variable x number;
    exec dbms_java.set_output(100000);
    exec :x := RUN_CMD('ipconfig');
    exec :x := RUN_CMD('d:a.bat') ;

0
相关文章