java 实现往oracle存储过程中传递array数组类型的参数

注:本文来源于 《  java 实现往oracle存储过程中传递array数组类型的参数  》

最近项目中遇到通过往存储过程传递数组参数的问题, 

浪费了N多个小时,终于有点头绪。 

具体的代码就不写上了,因为项目中存储过程的调用方法全部是封装好的(好像现在都这样,都姓3层,嘿嘿) 

原理:

1.一维数组

A.单纯的一维数组的话,直接建立一个table类型就可以 

  1 TYPE TYPE_VARCHAR AS TABLE OF VARCHAR2(200);

2.多维数组

A.多维数组就要稍加修改了,如二维数组 

  1 TYPE TYPE_VARCHAR AS TABLE OF VARCHAR2(200);
2
3 TYPE TYPE_TABLE AS TABLE OF TYPE_VARCHAR;

3.java代码的实现

A。首先是connection的问题,connection必须是OracleConnection(java.sql包下的) 

B。必须给Array添加一种数据定义(oracle.sql.ArrayDescriptor) 

C。ARRAY必须是java.sql.Array 

D。好了,开始定义ARRAY 

arrDesc
= ArrayDescriptor.createDescriptor("TYPE_TABLE",
getNativeConnection(conn)); 
  ARRAY arr = new ARRAY(arrDesc, getNativeConnection(conn), new
Object[][]{{"test1","test2"},{"testA","testB"}}); 

从网上搜到为数不多的代码(仅供参考) 

下面代码来自ChinaUnix博客(http://blog.chinaunix.net/u2/63586/showart_703439.html) 

  1 -----------------------------------------------------------------------------------
2 import java.sql.Connection;
3 import java.sql.PreparedStatement;
4 import java.sql.CallableStatement;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Types;
8 import java.util.ArrayList;
9 import oracle.sql.ARRAY;
10 import oracle.sql.ArrayDescriptor;
11 import org.apache.tomcat.dbcp.dbcp.DelegatingConnection;
12 public class BussinessLog {
13 public static ArrayList<Comparable> CancelLog(String sLoginUser, Object[] arrLogID)
14 {
15 ArrayList<Comparable> arrList = new ArrayList<Comparable>();
16 Connection conn = null;
17 CallableStatement callStmt = null;
18 String sql = null;
19 ArrayDescriptor arrDesc = null;
20
21 try
22 {
23 conn = DbConnectionManager.getConnection();
24 sql = "{call P_CanceltLog(?,?,?,?)}";
25 callStmt = conn.prepareCall(sql);
26 arrDesc = ArrayDescriptor.createDescriptor("NUMBERTABLE", getNativeConnection(conn));
27 ARRAY arr = new ARRAY(arrDesc, getNativeConnection(conn), arrLogID);
28 callStmt.setString(1, sLoginUser);
29 callStmt.setObject(2, arr, Types.ARRAY);
30 callStmt.registerOutParameter(3, Types.VARCHAR);
31 callStmt.registerOutParameter(4, Types.INTEGER);
32 callStmt.execute();
33
34 arrList.add(callStmt.getInt(4));
35 arrList.add(callStmt.getString(3));
36 return arrList;
37 } catch (Exception e) {
38 System.out.println(e.toString());
39 } finally {
40 DbAction.clear(conn, callStmt);
41 }
42 return arrList;
43 }
44
45 public static Connection getNativeConnection(Connection con) throws SQLException {
46 if (con instanceof DelegatingConnection) {
47 Connection nativeCon = ((DelegatingConnection) con).getInnermostDelegate();
48 return (nativeCon != null ? nativeCon : con.getMetaData().getConnection());
49 }
50 return con;
51 }
52 }
上一篇:cocos2dx-是男人就坚持20s 练手项目


下一篇:Ubuntu 11.04安装arm-linux-gcc-4.4.3/arm-none-linux-gnueabi-gcc安装包