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

私の知る限り、。SqlCommandというプロパティやフィールドはありませんSelectCommand。ただそれを取り除く:

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

SelectCommandそのようなプロパティはありません。上記のように直接使用してください。

于 2011-12-31T00:39:14.493 に答える