C#中如何获取存储过程的输出参数值

在程序中,有时数据访问层要调用存储过程,那么,在存储过程中如何调用及如何获取存储过程的输出参数值呢?下面是C#代码的实现

1.运用Command对象


[c-sharp] view plain copy
  1. SqlConnection con = new SqlConnection(constring);//constring是连接字符串

  2. con.Open();  

  3. string sql = "myproc";   //存储过程名称myproc

  4. SqlCommand com = new SqlCommand(sql,con);  

  5. //设置Command对象的类型

  6. com.CommandType = CommandType.StoredProcedure;  

  7. SqlParameter output =  

  8.            com.Parameters.Add("@i", SqlDbType.Int);  //添加参数

  9. //设置参数类型

  10. output.Direction = ParameterDirection.Output;  

  11. //执行

  12. com.ExecuteNonQuery();              

  13. //获取输出参数值对界面文体框

  14. this.textBox1.Text = (output.Value).ToString();  

  15. //另一种写法

  16. //this.textBox1.Text = com.Parameters["@i"].Value.ToString();

  17. con.Close();  



2.运用DataAdapter对象


[c-sharp] view plain copy
  1. DataSet ds = new DataSet();  

  2. string sql = "myproc";   //存储过程名称myproc

  3. SqlDataAdapter da = new SqlDataAdapter(sql, con);  

  4. //添加参数

  5. SqlParameter accp =  

  6.        da.SelectCommand.Parameters.Add("@i", SqlDbType.Int);  

  7. //设置参数类型

  8. accp.Direction = ParameterDirection.Output;    

  9. //设置命令对象类型        

  10. da.SelectCommand.CommandType = CommandType.StoredProcedure;  

  11. //填充数据

  12. da.Fill(ds);  

  13. this.dataGridView1.DataSource = ds.Tables[0];  

  14. //获取参数值给文本框

  15. this.textBox2.Text = da.SelectCommand.Parameters[0].Value.ToString();  



你可能感兴趣的:(存储过程,输出参数)