日期:2014-05-16 浏览次数:20471 次
drop table T_VarcharArray; create table T_VarcharArray( id number(10), name varchar2(100) );
drop type T_VARCHAR; create or replace type T_VARCHAR as table of varchar2(100);
drop type T_NUMBER; create or replace type T_NUMBER as table of number(10); create or replace procedure P_VARCHAR2_LST( i_t_varchar IN t_varchar, --输入参数为定义的不定长varchar2数组 o_n_ret OUT number --输出参数,正常结束,则输出0,否则抛出异常 ) is begin FOR i in 1..i_t_varchar.COUNT loop --注意下标从1开始。 insert into T_VarcharArray values (i,i_t_varchar(i)); end loop; o_n_ret :=0; exception when others then raise; end; / create or replace function F_NUMBER_LST( i_t_number IN t_number --输入参数为定义的不定长数值数组 ) return number --函数输出结果 is begin FOR i in 1..i_t_number.COUNT loop --注意下标从1开始。 insert into T_VarcharArray values (i_t_number(i),to_char(i)); end loop; return 0; exception when others then raise; end;
package test.oracle.oj; import java.sql.*; import oracle.jdbc.driver.OracleTypes; import oracle.sql.ARRAY; import oracle.sql.ArrayDescriptor; import test.oracle.conn.OConnection; public class Varchar2NumberArray { // 注意:T_VARCHAR2必须全部大写 private static final String T_VARCHAR = "T_VARCHAR"; private static final String T_NUMBER = "T_NUMBER"; // 注意:call必须小写,过程名字必须全部大写 private static final String P_VARCHAR2_LST = "{call P_VARCHAR2_LST(?,?)}"; // 注意:call必须小写,过程名字必须全部大写,返回值在java中是第一个 private static final String F_NUMBER_LST = "{? = call F_NUMBER_LST(?)}"; public static int varchar2LstTest(String[] lst) { int retVal = -1; Connection con = null; CallableStatement cstmt = null; try { con = OConnection.getConn(); // 创建一个数组描述符 ArrayDescriptor varchar2Desc = ArrayDescriptor.createDescriptor( T_VARCHAR, con); // 将字符串数组转换为oralce能识别的数组 ARRAY vArray = new ARRAY(varchar2Desc, con, lst); cstmt = con.prepareCall(P_VARCHAR2_LST); cstmt.setArray(1, vArray); cstmt.registerOutParameter(2, OracleTypes.INTEGER); cstmt.execute(); retVal = cstmt.getInt(2); } catch (Exception ex) { ex.printStackTrace(); } finally { // 最好都在finally里面关闭用到的cs、ps、rs以及con, // 以确保出异常时,该释放的都被释放 try { if (cstmt != null) { cstmt.close(); } if (con != null) { con.close(); } } catch (SQLException sqle) { sqle.printStackTrace(); } } return retVal; } public static int numberLstTest(int[] lst) { int retVal = -1; Connection con = null; CallableStatement cstmt = null; try { con = OConnection.getConn(); // 创建一个数组描述符 ArrayDescriptor varchar2Desc = ArrayDescriptor.createDescriptor( T_NUMBER, con); // 将字符串数组转换为oralce能识别的数组 ARRAY vArray = new ARRAY(varchar2Desc, con, lst); cstmt = con.prepareCall(F_NUMBER_LST); // 返回值在java中是第一个,所以先注册输出参数 cstmt.registerOutParameter(1, OracleTypes.INTEGER); cstmt.setArray(2, vArray); cstmt.execute(); retVal = cstmt.getInt(1); } catch (Except