Oracle中table变量在JDBC中的运用

10 篇文章 0 订阅

 http://www.2cto.com/database/201109/102884.html

1.先定义一个返回数组类型的方法
create or replace type my_table_type is table of varchar2(20);
 
create or replace function func
return my_table_type
is
i my_table_type:=my_table_type();
begin
    select name bulk collect into i from emps;
    return i;
end;
 
2.在JDBC中调用,如果返回的是table变量
 
Java代码 
public void SelectAgus(String sql) 
    { 
         OracleCallableStatement call = null; 
         try 
         {   
             call = (OracleCallableStatement) con.prepareCall(sql); 
             //如果返回的是table则用ARRAY类型,如果返回的是OBJECT的就用STRUCT 
             //第三个参数是定义table的类型名 
             call.registerOutParameter(1, OracleTypes.ARRAY,"MY_TABLE_TYPE"); 
             call.execute(); 
             //获取第一个参数(这里即返回值) 
             ARRAY array = call.getARRAY(1); 
             //获取表中的元素 
             Datum[] dat = array.getOracleArray(); 
             //遍历依次打印 
             for(Datum d : dat) 
             { 
                 System.out.println(new String(d.getBytes())); 
             } 
         }catch(Exception e) 
         { 
             e.printStackTrace(); 
         } 
    } 
   2.如果定义的是嵌套表结构,
   如下定义:
   create or replace type all_table is object(id number,name varchar2(20));
create or replace type emps_table_type is table of all_table;
--创建一个函数,返回类型为emps_table_type;
create or replace function funcc
return emps_table_type
is
i emps_table_type;
begin
   --把emps中的ID,NAME属性值全部读取到i中
   select all_table(id,name) bulk collect into i from emps;
   return i;--返回table
end;


   
Java代码 
public void SelectAgus(String sql) 
    { 
        OracleCallableStatement call = null; 
        try 
        { 
            call = (OracleCallableStatement) con.prepareCall(sql); 
            call.registerOutParameter(1, OracleTypes.ARRAY,"EMPS_TABLE_TYPE"); 
            call.execute(); 
            ARRAY array = call.getARRAY(1); 
            Datum[] dat = array.getOracleArray(); 
            for(Datum d : dat) 
            {   //获取了行后,要获取一行中的元素 
                STRUCT struct = (STRUCT)d; 
                //这里有可能会出现乱码,所以我分别用了两种方式获取元素 
                Datum[] d1 = struct.getOracleAttributes(); 
                Object[] d2 = struct.getAttributes(); 
                System.out.println("ID="+d2[0]+"  "+"NAME="+ 
                        new String(d1[1].getBytes())); 
            } 
             
        }catch(Exception e){ 
            e.printStackTrace(); 
        } 
    } 

 

作者“aazham”

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值