我收到错误“必须声明标量变量@IdAlbum”。我已经在这个主题上发过类似的帖子,但它没有帮助。有人可以查看下面的代码吗?当我使用命令参数时,它给了我错误。如果我不使用命令参数,它工作正常。我已在代码中添加注释以突出显示问题所在。
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;
}
答案 0 :(得分:2)
看看这个:https://msdn.microsoft.com/en-us/library/ebxy9a8b(v=vs.80).aspx
你做错了,你应该使用DataAdapter填充缺少的参数。
再看看这个问题和答案,它提供了很好的解释:c# Using Parameters.AddWithValue in SqlDataAdapter