ExecuteScalar编译错误

本文关键字:错误 编译 ExecuteScalar | 更新日期: 2023-09-27 18:15:27

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

ExecuteScalar编译错误

我想你已经定义了参数@ pictuid但是你在查询中使用了变量名@PicId

试题:

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

如何声明一个标量变量?

这是你的声明代码

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

,在这种情况下,您必须将PicID更改为PicID

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