使用会话和查询字符串进行参数化

时间:2014-07-02 20:03:22

标签: c# asp.net session query-string

我正面临一条错误消息,我不知道我在sql语句中的原因如下:

DACatPgeVIPLIST.Fill(dsCatPgeVIPLIST);

显示此消息可以帮助我:

  

参数化查询(@Country nvarchar(7),@Category nvarchar(4000))SELECT a.[AdsID],需要参数@Category,该参数未提供。

代码:

if (Session["location"] != null)
{
    using (SqlConnection CatPgeVIPLISTsqlCON = new SqlConnection(cs))
    {
        CatPgeVIPLISTsqlCON.Open();

        SqlDataAdapter DACatPgeVIPLIST = new SqlDataAdapter("SELECT a.[AdsID], a.[Country], a.[State], a.[City], a.[AdsTit], SUBSTRING(a.[AdsDesc], 1, 70) as AdsDesc, a.[AdsPrice], a.[Img1] FROM [ads] as a INNER JOIN [UserInfo] as u on u.UID = a.UID WHERE a.[Country] = @Country and a.[Category] = @Category and u.VIP = 'Yes'", cs);

        string location = Convert.ToString(Session["location"]);
        string category = Request.QueryString["category"];

        DACatPgeVIPLIST.SelectCommand.Parameters.AddWithValue("@Country", location);
        DACatPgeVIPLIST.SelectCommand.Parameters.AddWithValue("@Category", category);

        DataSet dsCatPgeVIPLIST = new DataSet();

        DACatPgeVIPLIST.Fill(dsCatPgeVIPLIST);

        CatPgeVIPLIST.DataSource = dsCatPgeVIPLIST.Tables[0];
        CatPgeVIPLIST.DataBind();
    }
}

1 个答案:

答案 0 :(得分:1)

以下代码行可以将null分配给类别:

string category = Request.QueryString["category"];

你可能会像这样绕过它,将null转换为空字符串:

string category = Convert.ToString(Request.QueryString["category"]);

或者您可以尝试传递DBNull.Value而不是null(未经测试):

DACatPgeVIPLIST.SelectCommand.Parameters
               .AddWithValue("@Category", (object)category ?? DBNull.Value);