oracle執行java程式碼

zhouwf0726發表於2019-04-23

--需要確認資料庫系統已經選擇安裝了JAVA虛擬機器元件
--1、登陸SYS使用者,執行以下程式碼
begin
Dbms_Java.Grant_Permission('PSIID','java.io.FilePermission', '<>','read ,write, execute, delete');
Dbms_java.grant_permission('PSIID', 'SYS:java.io.FilePermission', '<>','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') ;


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/756652/viewspace-242161/,如需轉載,請註明出處,否則將追究法律責任。

相關文章