【问题标题】:Exception | must declare scalar variable @IdAlbum例外 |必须声明标量变量@IdAlbum
【发布时间】:2016-01-23 08:06:58
【问题描述】:

我收到一个错误“必须声明标量变量@IdAlbum”。我已经浏览过有关此主题的类似帖子,但没有帮助。有人可以看看下面的代码吗?当我使用命令参数时,它给了我错误。如果我不使用命令参数,它工作正常。我在代码中加入了 cmets 以突出问题所在。

 public DataSet databind ()
    {
        DataSet ds = new DataSet();
        string con_str = ConfigurationManager.ConnectionStrings["con_nc"].ConnectionString;
        SqlConnection con = new SqlConnection(con_str);
        try
        {

            con.Open();

            string albumId = Request.QueryString["AlbumId"].Trim();
            this.albumName = Request.QueryString["AlbumName"];

            //getting the count of the pictures from DB and assigning it to pagesize so that all pictures of single album come in 1 page only.

            string photoCountQuery = "select count(*) from gallery_photos where AlbumId=@albumId"; // THIS WORKS FINE


            SqlCommand picCount = new SqlCommand(photoCountQuery, con);// THIS WORKS FINE
            picCount.Parameters.AddWithValue("@albumID", albumId);// THIS WORKS FINE
            int photoCount = Convert.ToInt16(picCount.ExecuteScalar());// THIS WORKS FINE

            int start = (int)ViewState["start"];// THIS WORKS FINE
            ViewState["pagesize"] = photoCount;// THIS WORKS FINE

            //string query = "select * from gallery_photos where AlbumId='" + albumId + "'"; //// THIS WORKS FINE
            string query = "select * from gallery_photos where AlbumId=@IdAlbum";// THIS is the problem. It does not work when i use command paramters
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@IdAlbum", albumId);
            SqlDataAdapter da = new SqlDataAdapter(query, con);

            da.Fill(ds, start, (int)(ViewState["pagesize"]), "gallery_photos");


        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "Exception in " + Path.GetFileName(Page.AppRelativeVirtualPath).ToString());
            Context.ApplicationInstance.CompleteRequest();
        }
        finally
        {
            con.Close();
        }
        return ds;
    }

【问题讨论】:

    标签: asp.net sqldatasource sqldataadapter


    【解决方案1】:

    看看这个:https://msdn.microsoft.com/en-us/library/ebxy9a8b(v=vs.80).aspx

    你做错了,你应该使用DataAdapter来填充缺失的参数。

    也看看这个问题和答案,它提供了很好的解释:c# Using Parameters.AddWithValue in SqlDataAdapter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      相关资源
      最近更新 更多