4。訪問 Oracle 過程/函數(1)
SQL Server 作程式時經常使用預存程序,Oracle 裡也可以使用過程,還可以使用函數。Oracle 的過程似乎是不能有傳回值的,有傳回值的就是函數了(這點有些像 BASIC,函數/過程區分的很細緻。SQL Server 預存程序是可以有傳回值的)。
.NET 訪問 Oracle 過程/函數的方法很類似於 SQL Server,例如:
OracleParameter[] parameters = {
new OracleParameter("ReturnValue", OracleType.Int32, 0, ParameterDirection.ReturnValue, true, 0, 0, "",
DataRowVersion.Default, Convert.DBNull )
new OracleParameter("參數1", OracleType.NVarChar, 10),
new OracleParameter("參數2", OracleType.DateTime),
new OracleParameter("參數3", OracleType.Number, 1)
};
parameters[1].Value = "test";
parameters[2].Value = DateTime.Now;
parameters[3].Value = 1; // 也可以是 new OracleNumber(1);
OracleConnection connection = new OracleConnection( ConnectionString );
OracleCommand command = new OracleCommand("函數/程名", connection);
command.CommandType = CommandType.StoredProcedure;
foreach(OracleParameter parameter in parameters)
command.Parameters.Add( parameter );
connection.Open();
command.ExecuteNonQuery();
int returnValue = parameters[0].Value; //接收函數傳回值
connection.Close();
Parameter 的 DbType 設定請參見 System.Data.OracleClient.OracleType 枚舉的文檔,比如:Oracle 資料庫中 Number 類型的參數的值可以用 .NET decimal 或 System.Data.OracleClient.OracleNumber 類型指定; Integer 類型的參數的值可以用 .NET int 或 OracleNumber 類型指定。等等。
上面例子中已經看到函數傳回值是用名為“ReturnValue”的參數指定的,該參數為 ParameterDirection.ReturnValue 的參數。
5。訪問 Oracle 過程/函數 (2)
不返回記錄集(沒有 SELECT 輸出)的過程/函數,調用起來和 SQL Server 較為類似。但如果想通過過程/函數返回記錄集,在 Oracle 中就比較麻煩一些了。
在 SQL Server 中,如下的預存程序:
CREATE PROCEDURE GetCategoryBooks
(
@CategoryID int
)
AS
SELECT * FROM Books
WHERE CategoryID = @CategoryID
GO
在 Oracle 中,請按以下步驟操作:
(1)建立一個包,含有一個遊標類型:(一個資料庫中只需作一次)
CREATE OR REPLACE PACKAGE Test
AS
TYPE Test_CURSOR IS REF CURSOR;
END Test;
(2)過程:
CREATE OR REPLACE PROCEDURE GetCategoryBooks
(
p_CURSOR out Test.Test_CURSOR, -- 這裡是上面包中的類型,輸出參數
p_CatogoryID INTEGER
)
AS
BEGIN
OPEN p_CURSOR FOR
SELECT * FROM Books
WHERE CategoryID=p_CatogoryID;
END GetCategoryBooks;
(3).NET 程式中:
OracleParameters parameters = {
new OracleParameter("p_CURSOR", OracleType.CURSOR, 2000, ParameterDirection.Output, true, 0, 0, "",
DataRowVersion.Default, Convert.DBNull),
new OracleParameter("p_CatogoryID", OracleType.Int32)
};
parameters[1].Value = 22;
OracleConnection connection = new OracleConnection( ConnectionString );
OracleCommand command = new OracleCommand("GetCategoryBooks", connection);
command.CommandType = CommandType.StoredProcedure;
foreach(OracleParameter parameter in parameters)
command.Parameters.Add( parameter );
connection.Open();
OracleDataReader dr = command.ExecuteReader();
while(dr.Read())
{
// 你的具體操作。這個就不需要我教吧?
}
connection.Close();
另外有一點需要指出的是,如果使用 DataReader 取得了一個記錄集,那麼在 DataReader 關閉之前,程式無法訪問輸出參數和傳回值的資料。
好了,先這些,總之 .NET 訪問 Oracle 還是有很多地方和 SQL Server 不同的,慢慢學習了。