ExecuteScalar编译错误

时间:2011-11-21 00:36:25

标签: c# sql scalar executescalar

我在ExecuteScalar()收到错误。它说我必须声明标量变量@PicID。我怎么能宣布一个标量变量?或者我是否错误地完成了这整个功能?

 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 个答案:

答案 0 :(得分:2)

我认为你已经定义了@PictureId参数,但你在查询中使用了变量名@PicId

尝试:

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

答案 1 :(得分: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;