在调试PL/SQL中一段示例代码的过程中,学到了一个新的知识点:PL/SQL中调用Java代码(平台:WINDOWS)。
过程如下:
1.首先使用IDE写好需要调用的java代码,再添加"create or replace and compile java source named 名字 as",然后在PL/SQL中执行
SQL> /* Formatted on 2018/12/9 17:16:27 (QP5 v5.256.13226.35538) */
SQL> CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED getosmac
2 AS import java.io.InputStreamReader;
3 import java.io.LineNumberReader;
4
5 public class GetOSMac {
6 /**
7 * 获取MAC地址
8 */
9 public static String getMac() {
10 String result = "";
11 try {
12 Process process = Runtime.getRuntime().exec("ipconfig /all");
13 /**
14 * 通过执行dos命令IPCONFIG / ALL来获取
15 */
16 InputStreamReader ir = new InputStreamReader(
17 process.getInputStream());
18 LineNumberReader input = new LineNumberReader(ir);
19
20 String line;
21
22 while ((line = input.readLine()) != null)
23
24 if (line.indexOf("物理地址") > 0) {
25
26 String macAddr = line.substring(line.indexOf("-") - 2);
27
28 result = macAddr;
29
30 }
31 } catch (java.io.IOException e) {
32 System.err.println("IOException " + e.getMessage());
33 }
34
35 System.out.println("Mac:" + result);
36 return result;
37 }
38
39 public static void main(String[] args) {
40 getMac();
41 System.out.println("OK!!!");
42 }
43
44 }
45 /
Java 已创建。
2. 然后创建函数调用该JAVA SOURCE的Function
SQL> create or replace function GetMac return varchar2 is
2 language java name ' GetOSMac.getMac() return java.lang.String';
3 /
函数已创建。
3. 调用函数
SQL> select GetMac AS MAC from dual;
MAC
--------------------------------------------------------------------------------
46-42-21-B2-88-26
调试过程中会碰到一些问题,解决过程参考:
http://www.cnblogs.com/softidea/p/4885453.html
需注意:
以下问题的正确解决方法是在sys中执行以下授权语句:
ORA-29532: Java 调用被未捕获的 Java 异常错误终止:
java.security.AccessControlException: the Permission (java.io.FilePermission
<<ALL FILES>> execute) has not been granted to C##STUDENT. The PL/SQL to grant
this is dbms_java.grant_permission( 'C##STUDENT', 'SYS:java.io.FilePermission',
'<<ALL FILES>>', 'execute' )
SQL> EXEC Dbms_Java.Grant_Permission('C##STUDENT','SYS:java.io.FilePermission', '<<ALL FILES>>','execute');