调用Oracle存储过程并获取out参数值

原文:

http://tech.it168.com/oldarticle/2006-04-02/200604021512359.shtml

http://www.cnblogs.com/m-cnblogs/archive/2012/02/23/2364906.html

1.创建测试存储过程:
  SQL> create or replace procedure proc_test(p1 IN varchar2,p2 OUT varchar2) is
  2 begin
  3 SELECT p1 INTO p2 FROM dual;
  4 end proc_test;
  5 /

  过程被创建

2.主要C# 代码以及注意点:
  using ORAC = System.Data.OracleClient;
  private void button1_Click(object sender, System.EventArgs e)
  {
    try
    {
      string str_Sql = @"call proc_test(:p1,:p2)"; 
      /*不能用:call proc_test(?,?)或者call proc_test(@p1,@p2),这样会报ORA-01036:非法的变量名/编号错误 */
      ORAC.OracleCommand cmd = new ORAC.OracleCommand(str_Sql,this.oracleConnection1);
      /*cmd.CommandType = CommandType.StoredProcedure;-注意这种方式调用存储过程,不能指定CommandType为StoredProcedure */

      ORAC.OracleParameter pram1 = new ORAC.OracleParameter("p1",ORAC.OracleType.VarChar,10);
      pram1.Value = "test";

      cmd.Parameters.Add(pram1);

      ORAC.OracleParameter pram2 = new ORAC.OracleParameter("p2",ORAC.OracleType.VarChar,10);
      pram2.Direction =ParameterDirection.Output;

      cmd.Parameters.Add(pram2);

      if(this.oracleConnection1.State == System.Data.ConnectionState.Closed)
      {
        this.oracleConnection1.Open();
      }

      cmd.ExecuteNonQuery();

      this.textBox1.Text = cmd.Parameters[1].Value.ToString();
    }
    catch(Exception ex)
    {
      MessageBox.Show(ex.Message);
    }
    finally
    {
      this.oracleConnection1.Close();
    }
  }

参数说明

parameter.Value=赋值

当这个值为null时,不能直接赋值,负责页面就会报错:未将对象应用到对象的实例

当为null时需转化为System.DBNull.Value即可

原文地址:https://www.cnblogs.com/xcsn/p/4548715.html