0

如何在下面的代码中正确声明参数。我在“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);
        }

    }
4

3 回答 3

4

你做错了几件事;

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

2) 您在不需要时使用 SelectCommand 属性。事实上,您可能会将其与具有 SelectCommand 属性的DataAdapter对象混淆。

相反,请尝试:

    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”语句。它将确保您的连接在离开范围后立即关闭和处置,包括在异常之后。

于 2011-12-31T00:38:02.853 回答
0
oCommand.Parameters.Add("@dSexType", SqlDbType.Text);
oCommand.Parameters["@dSexType"].Value = SexType;

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

于 2011-12-31T00:39:14.493 回答
0

据我所知SqlCommand,没有名为SelectCommand. 摆脱它:

oCommand.Parameters.Add("@dSexType", SqlDbType.Text);
oCommand.Parameters["@dSexType"].Value = SexType;
于 2011-12-31T00:37:04.327 回答