2011-12-31 27 views
0

以下のコードでパラメータを正しく宣言する方法を教えてください。 Imは "SelectCommand"に下線を引いています。何が間違っているのかわかりません。私の知る限りSqlCommandコマンドパラメータの選択を選択してください

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); 
     } 

    } 
+0

あなたのIDEは、利用可能でない場合、プロパティのリストをポップアップするのに十分なほどスマートです。どのようにそのような声明を書いたのですか – Lion

+0

+1をランダムにオフセットする(説明なし) –

答えて

4

あなたはいくつかのことを間違っている。

1)あなたがする必要はありませんときは、SelectCommandプロパティを使用している)クエリ

2を実行後のパラメータを追加しています。実際には、おそらくこれを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"ステートメントを使用して、あなたを促すだろう。例外が発生した場合を含め、スコープを離れるとすぐに接続が閉じられ、破棄されます。

+0

+1 for 'ステートメント。 – keyboardP

0

SelectCommandと呼ばれるプロパティまたはフィールドを持っていません。ちょうどそれを取り除く:

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

SelectCommandにはこのような特性はありません。上記のように直接使用してください。

関連する問題