使用SqlCommand对象执行存储过程

前面我们介绍使用 SqlCommand 执行一个参数化的SQL语句,现在我们来学习如何使用SqlCommand执行存储过程。为了能更灵活地指定参数,我们在页面上添加两个文本框,tbClassName 和 tbBoardname,和一个用于添加版块的按钮 btn_AddBoard,双击添加按钮Click事件处理程序。

    protected void Button1_Click(object sender, EventArgs e)
    {
        string sConnectionString = @"Server=(local)\SQLEXPRESS;database=Forum;Trusted_Connection=True";
        using (SqlConnection conn = new SqlConnection(sConnectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("CreateBoard", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@ClassName", SqlDbType.VarChar, 50);
                cmd.Parameters["@ClassName"].Value = tbClassName.Text;
                cmd.Parameters["@ClassName"].Direction = ParameterDirection.Input;
                cmd.Parameters.Add("@BoardName", SqlDbType.VarChar, 50);
                cmd.Parameters["@BoardName"].Value = tbBoardName.Text;
                cmd.Parameters["@BoardName"].Direction = ParameterDirection.Input;
                cmd.Parameters.Add("@ClassID", SqlDbType.VarChar, 50);
                cmd.Parameters["@ClassID"].Direction = ParameterDirection.Output;
                cmd.Parameters.Add("@BoardCount", SqlDbType.Int);
                cmd.Parameters["@BoardCount"].Direction = ParameterDirection.ReturnValue;
                cmd.ExecuteNonQuery();
                foreach (SqlParameter parameter in cmd.Parameters)
                {
                    Response.Write(string.Format("参数名: {0}, 参数方向: {1}, 参数值: {2}<br />", parameter.ParameterName, parameter.Direction.ToString(), parameter.Value));
                }
            }
        }

  在这段代码中,要注意以下几点。

  1. CommandType 枚举。用来枚举所有的命令类型,默认是 CommandType.Text,用于执行SQL语句。如果我们把SqlCommand 的 CommandText 设置为一个存储过程名,则应该指字 CommandType 为 CommandType.StoredProcedure。

  2. Parameters 集合。我们需要把所有存储过程需要的参数都添加到 SqlCommand 的 SqlParameterCollection 集合中去,参数名、参数类型和参数大小都应该和存储过程中声明的参数对应。

  3. 参数的类型和值。对于输入参数,我们可以通过Parameter的Value属性为其指定一个值。我们注意到,这个值可以是任意类型的。对于输出参数和返回参数,在存储过程执行以前它们的值都为空,在存储过程执行以后,我们可以通过再次访问 SqlParameterCollection 集合来获取参数的值。

  我们看到,@ClassID输出参数的值被设置成了 @ClassName 参数对应的分类的分类ID;@BoardCount返回参数的值被设置成 tbBoard表中记录的总数。

原文地址:https://www.cnblogs.com/hulang/p/1920650.html