2011-12-31 77 views
0

如何正確declair在下面的代碼的參數。即時得到的「的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); 
     } 

    } 
+0

你的IDE是足夠聰明,沒有如果沒有,則彈出的屬性列表。你是怎麼寫這樣的陳述的? – Lion 2011-12-31 00:41:59

+0

+1抵消隨機-1(不解釋)爲'using'聲明 – 2011-12-31 00:50:55

回答

4

你正在做一些錯誤的事情;

1)要添加的參數後,你執行你正在使用SelectCommand屬性,當你不需要查詢

2)。事實上,你可能有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"聲明。這將確保您的連接被關閉,因爲一旦離開的範圍,其中包括一個異常後丟棄。

+0

+1。 – keyboardP 2011-12-31 00:38:35

0

據我所知SqlCommand沒有一個叫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沒有這樣的屬性。直接像上面一樣使用。