原文地址:http://qihang.net/u/fesing/Blog/t-1845
最近項目中遇到通過往存儲過程傳遞數(shù)組參數(shù)的問題,
浪費了N多個小時,終于有點頭緒。
具體的代碼就不寫上了,因為項目中存儲過程的調(diào)用方法全部是封裝好的(好像現(xiàn)在都這樣,都姓3層,嘿嘿)
原理:
1.一維數(shù)組
A.單純的一維數(shù)組的話,直接建立一個table類型就可以
TYPE TYPE_VARCHAR AS TABLE OF VARCHAR2(200);
2.多維數(shù)組
A.多維數(shù)組就要稍加修改了,如二維數(shù)組
TYPE TYPE_VARCHAR AS TABLE OF VARCHAR2(200);
TYPE TYPE_TABLE AS TABLE OF TYPE_VARCHAR;
3.java代碼的實現(xiàn)
A。首先是connection的問題,connection必須是OracleConnection(java.sql包下的)
B。必須給Array添加一種數(shù)據(jù)定義(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"}});
從網(wǎng)上搜到為數(shù)不多的代碼(僅供參考)
下面代碼來自ChinaUnix博客(http://blog.chinaunix.net/u2/63586/showart_703439.html)
-----------------------------------------------------------------------------------
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import org.apache.tomcat.dbcp.dbcp.DelegatingConnection;
public class BussinessLog {
public static ArrayList<Comparable> CancelLog(String sLoginUser, Object[] arrLogID)
{
ArrayList<Comparable> arrList = new ArrayList<Comparable>();
Connection conn = null;
CallableStatement callStmt = null;
String sql = null;
ArrayDescriptor arrDesc = null;
try
{
conn = DbConnectionManager.getConnection();
sql = "{call P_CanceltLog(?,?,?,?)}";
callStmt = conn.prepareCall(sql);
arrDesc = ArrayDescriptor.createDescriptor("NUMBERTABLE", getNativeConnection(conn));
ARRAY arr = new ARRAY(arrDesc, getNativeConnection(conn), arrLogID);
callStmt.setString(1, sLoginUser);
callStmt.setObject(2, arr, Types.ARRAY);
callStmt.registerOutParameter(3, Types.VARCHAR);
callStmt.registerOutParameter(4, Types.INTEGER);
callStmt.execute();
arrList.add(callStmt.getInt(4));
arrList.add(callStmt.getString(3));
return arrList;
} catch (Exception e) {
System.out.println(e.toString());
} finally {
DbAction.clear(conn, callStmt);
}
return arrList;
}
public static Connection getNativeConnection(Connection con) throws SQLException {
if (con instanceof DelegatingConnection) {
Connection nativeCon = ((DelegatingConnection) con).getInnermostDelegate();
return (nativeCon != null ? nativeCon : con.getMetaData().getConnection());
}
return con;
}
}