当前位置:数据库 > SQLServer >>

使用PL/SQL执行OS命令

使用PL/SQL执行OS命令
 
[sql] 
create or replace and compile java source named ExeSysCommand as  
import java.io.*;  
public class ExeSysCommand  
{  
  public static String ExeCmd(String args) {  
        Runtime run = Runtime.getRuntime();  
        Process process = null;  
        try {  
            process = run.exec(args); // 执行cmd命令  
            return "OK!";  
        } catch (Exception e) {  
            return e.getMessage();  
        }  
        }  
  public static void main(String[] args)  
  {  
    System.out.println("No command line arguments");  
  }  
}  

 

 
其后创建函数调用该java soure
[sql] 
CREATE OR REPLACE FUNCTION ExeCmd(cmd STRING) RETURN VARCHAR2 IS --执行OS命令测试  
  LANGUAGE JAVA NAME ' ExeSysCommand.ExeCmd(java.lang.String) return java.lang.String';  

 

注意:有参数cmd,对应java的输入类型应当为java.lang.String.
还应当注意的是这些应当在SYS用户下操作,如果在其他用户下,会获得错误:
the Permission (java.io.FilePermission <<ALL FILES>> execute) has not been granted to SCOTT. The PL/SQL to grant this is dbms_java.grant_permission( 'SCOTT', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'execute' )
如果确实需要其他用户来执行,可以使用dbms_java.grant_permission来给相应用户赋权限.
 
下面是在windows环境下操作:
C:\Documents and Settings\Administrator>tasklist | find "calc"
先确认系统当前没有运行计算器程序.
好,让我们来用刚建立的plsql函数execmd来运行这个计算器程序.
[plain] 
C:\Documents and Settings\Administrator>sqlplus / as sysdba  
  
SQL*Plus: Release 11.2.0.1.0 Production on 星期三 7月 10 17:26:17 2013  
  
Copyright (c) 1982, 2010, Oracle.  All rights reserved.  
  
  
连接到:  
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production  
With the Partitioning, OLAP, Data Mining and Real Application Testing options  
  
17:26:17 SYS@orcl> select execmd('calc') from dual;  
  
EXECMD('CALC')  
-----------------------------------------------------------------------------------------  
  
OK!  

 

  
已用时间:  00: 00: 00.06  
17:26:37 SYS@orcl> host  
Microsoft Windows XP [版本 5.1.2600]  
(C) 版权所有 1985-2001 Microsoft Corp.  
  
C:\Documents and Settings\Administrator>tasklist | find "calc"  
calc.exe                   12000 Console                 0      3,052 K  

 

好了,我们看到计算器程序已经在运行了,但是非常不如意的是,没有界面出来。。。
我猜想可能是由于Oracle最早是基于linux开发,而且和MS是死对头(相关信息请查询Oracle的发家史...),所以没有考虑过支持WIN界面.
--
不过就算这样,也很方便了,我们可以建立定时JOB,通过PL/SQL来调用OS上的任何程序/脚本等做相关的任务了.
Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,