选择命令参数问题

时间:2011-12-31 00:32:48

标签: c# sql parameters executescalar

如何在下面的代码中正确声明参数。我在“SelectCommand”上强调了我不知道我做错了什么。

 public int GetTotalNumberOfAprovedPictureIds(string SexType)
    {
        string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"];

        SqlConnection conn = new SqlConnection(strConectionString);
        conn.Open();
        SqlCommand oCommand = new SqlCommand("SELECT COUNT(1) AS Expr1 FROM MEMBERS INNER JOIN Picture ON MEMBERS.MemberID = Picture.MemberID WHERE (Picture.PicAproval = 1) AND (Picture.PicArchive = 0) AND (MEMBERS.MemberSex = @dSexType)", conn);


        object oValue = oCommand.ExecuteScalar();

        oCommand.SelectCommand.Parameters.Add("@dSexType", SqlDbType.Text);
        oCommand.SelectCommand.Parameters["@dSexType"].Value = SexType;

        conn.Close();

        if (oValue == DBNull.Value)
        {
            return 0;
        }
        else
        {
            return Convert.ToInt32(oValue);
        }

    }

3 个答案:

答案 0 :(得分:4)

你做错了几件事;

1)您在执行查询后添加参数

2)当您不需要时,您正在使用SelectCommand属性。实际上,您可能会将此与DataAdapter对象混淆,后者具有SelectCommand属性。

相反,请尝试:

    public int GetTotalNumberOfAprovedPictureIds(string SexType)
    {
        string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"];

        using (SqlConnection conn = new SqlConnection(strConectionString))
        {
            conn.Open();
            using (SqlCommand oCommand = new SqlCommand("SELECT COUNT(*) FROM MEMBERS INNER JOIN Picture ON MEMBERS.MemberID = Picture.MemberID WHERE (Picture.PicAproval = 1) AND (Picture.PicArchive = 0) AND (MEMBERS.MemberSex = @dSexType)", conn))
            {
                oCommand.CommandType = CommandType.Text;
                SqlParameter myParam = oCommand.Parameters.Add("@dSexType", SqlDbType.Text);
                myParam.Value = SexType;

                object oValue = oCommand.ExecuteScalar();

                if (oValue == DBNull.Value)
                {
                    return 0;
                }
                else
                {
                    return Convert.ToInt32(oValue);
                }
            }
        }

    }

我强烈建议您在处理SqlConnection,SqlCommand和类似对象时使用"USING"语句。它将确保您的连接在离开范围时立即关闭并处理,包括在异常之后。

答案 1 :(得分:0)

据我所知SqlCommand没有名为SelectCommand的属性或字段。摆脱它:

oCommand.Parameters.Add("@dSexType", SqlDbType.Text);
oCommand.Parameters["@dSexType"].Value = SexType;

答案 2 :(得分:0)

oCommand.Parameters.Add("@dSexType", SqlDbType.Text);
oCommand.Parameters["@dSexType"].Value = SexType;

SelectCommand没有这样的属性。像上面那样直接使用。