2011年9月14日

如何用C#呼叫Oracle function/procedure

以下程式碼是範如何用C#呼叫Oracle function/procedure, 參數若有out不能用select from dual來抓回傳值。
另外可參考如何建立oracle function
以下是C#範例:

        protected void Page_Load(object sender, EventArgs e)
        {
            string connString = getConnectionString();
            this.Label1.Text = connString;
            int res;
            //建立connection
            OracleConnection conn = new OracleConnection(connString);
            conn.Open();
            

            //建立command呼叫function: "testFun"
            OracleCommand cmd = new OracleCommand("TESTFUN", conn);
            //設定command type為StoredProcedure
            cmd.CommandType = CommandType.StoredProcedure;


            cmd.Parameters.Add(new OracleParameter("ret", OracleType.Int32));
            cmd.Parameters["ret"].Direction = ParameterDirection.ReturnValue;
            //加入參數no_in
            cmd.Parameters.Add( new OracleParameter("NO_IN", OracleType.Int32));
            //參數方向in/out/in out
            cmd.Parameters["NO_IN"].Direction = ParameterDirection.InputOutput;
            //參數值
            cmd.Parameters["NO_IN"].Value = 1;

            
            //執行命令, 並傳回回傳值
           cmd.ExecuteNonQuery();


            //顯示參數no_in
            this.Label2.Text = cmd.Parameters["NO_IN"].Value.ToString();
            //顯示回傳值
            this.Label3.Text = cmd.Parameters["ret"].Value.ToString();
            conn.Close();


        }
        //get connection string
        private string getConnectionString()
        {
            System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/WebOracle");
            System.Configuration.ConnectionStringSettings connString;
            if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
            {
                connString = rootWebConfig.ConnectionStrings.ConnectionStrings["CONN_ORACLE"];
                if (null != connString)
                    return connString.ConnectionString;
                else
                    return ("No connection string");
            }
            else
                return "";

        }


參考



http://msdn.microsoft.com/zh-tw/library/ms178411(VS.80).aspx


https://forums.oracle.com/forums/thread.jspa?threadID=874314


http://p2p.wrox.com/c/8762-call-function-oracle-c.html

沒有留言:

張貼留言