2011-11-21 64 views
-1

我在ExecuteScalar()上收到錯誤消息。它說我必須聲明標量變量@PicID。我怎麼能聲明一個標量變量?或者我不正確地完成整個功能?ExecuteScalar編譯錯誤

public int GetTotalNoVotes(int PicRating, int PicID) 
    { 
     //get database connection string from config file 
     string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"]; 

     SqlConnection conn = new SqlConnection(strConectionString); 
     conn.Open(); 

     SqlCommand oCommand = new SqlCommand("SELECT COUNT(1) AS Expr1 FROM Ratings WHERE PicRating = @PicRating) AND (PicID = @PicID)", conn); 
     oCommand.Parameters.Add("@PictureID", SqlDbType.Int); 
     oCommand.Parameters["@PictureID"].Value = PicID; 

     oCommand.Parameters.Add("@PicRating", SqlDbType.Int); 
     oCommand.Parameters["@PicRating"].Value = PicRating; 

     object oValue = oCommand.ExecuteScalar(); 

     conn.Close(); 

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

有添加參數的SqlCommand快捷方式:oCommand。 Parameters.Add(「@ PictureID」,SqlDbType.Int).Value = PicID; – 2011-11-21 01:02:35

回答

2

我想你已經定義的參數@PictureId但你使用的變量名@PicId查詢

嘗試:

SqlCommand oCommand = new SqlCommand("SELECT COUNT(1) AS Expr1 FROM Ratings WHERE PicRating = @PicRating) AND (PicID = @PictureID)", conn);  
1

我會怎樣宣佈一個可變的縮放?

這裏是你的聲明代碼

oCommand.Parameters.Add("@PictureID", SqlDbType.Int); 
oCommand.Parameters["@PictureID"].Value = PicID; 

在這種情況下,你必須將PictureID改變PicID

oCommand.Parameters.Add("@PicID", SqlDbType.Int); 
oCommand.Parameters["@PicID"].Value = PicID;