日历

2008 8.20 Wed
     12
3456789
10111213141516
17181920212223
24252627282930
31      
«» 2008 - 8 «»

文章搜索

日志文章

2007年08月21日 15:47:54

存储过程在C#中的使用(2)

上篇文章已经讲了存储过程输入参数在C#中的具体应用,接下这篇将讨论存储过程输出参数在C#中的应用.
首先理所当然还是创建一个带输出参数的存储过程.代码如下:
CREATE procedure TestProcedure
@id int,
@uname varchar(20) output--输出参数
as
select @uname=uname from [user] where @id=id;
GO

接下来是在C#中的具体操作.
脱了个界面一个文本框,textBox1,用来输入id,一个按钮(button1)用来显示输出参数的值.
代码如下:
private void button1_Click(object sender, EventArgs e)
  {
    select(int.Parse(this.textBox1.Text));//传值,调方法
  }
  public void select(int id)//一个方法
  {
    using (SqlConnection con = new SqlConnection(connstring))
    {
      con.Open();
      string sql = string.Format("Exec TestProcedure {0},@uname output", id);
      SqlCommand com = new SqlCommand(sql, con);
    SqlParameter sp = new SqlParameter("@uname", SqlDbType.VarChar, 20);
      sp.Direction = ParameterDirection.Output;
      com.Parameters.Add(sp);
      com.ExecuteNonQuery();
      con.Close();
      string result = sp.Value.ToString();//得到值
      MessageBox.Show(result.ToString());//显示输出参数的值
    }
  }

OK,搞定.

Tags: 输出参数  

类别: C# |  评论(0) |  浏览(1867) |  收藏
发表评论