忽略查询中的某些文本框

时间:2012-12-25 14:52:13

标签: asp.net sql report

我在btnShowReport_Click的代码后面有以下代码:

SqlDataSource1.SelectParameters.Clear();  
SqlDataSource1.SelectParameters.Add("username", txtUsername.Text);  
SqlDataSource1.SelectParameters.Add("printer", ddlPrinter.Text);  
SqlDataSource1.SelectParameters.Add("to", Date.convertDateSolar2Gregorian(txtDateFrom_datepicker.Text));
SqlDataSource1.SelectParameters.Add("from", Date.convertDateSolar2Gregorian(txtDateTo_datepicker.Text));
SqlDataSource1.SelectCommand = "SELECT * FROM JobLog WHERE UserName=@username and   PrinterName=@printer and TimeSubmitted between @to and @from";  

我想当用户没有填写一些文本框时,在查询中,查询中忽略了文本框的条件。 我希望你明白我的意思。

2 个答案:

答案 0 :(得分:2)

您可以使用StringBuilder动态构建SQL查询,但这会使您的代码容易受到SQL注入攻击,您应该考虑使用Dynamic SQL

这是StringBuilder示例,但如果您必须在代码中构建查询:

  protected void Page_Load(object sender, EventArgs e)
{
    Dictionary<string, string> parameters = new Dictionary<string, string>();
    SqlDataSource1.SelectParameters.Clear();

    string name = txtName.Text;
    string surname = txtSurname.Text;

    if (name.Length > 0)
    {
        SqlDataSource1.SelectParameters.Add("Name", txtName.Text);
        parameters.Add("Name", name);
    }

    if (surname.Length > 0)
    {
        SqlDataSource1.SelectParameters.Add("Surname", txtSurname.Text);
        parameters.Add("Surname", surname);
    }

    SqlDataSource1.SelectCommand = GetSelectQuery("Customers", parameters);
    //Bind SqlDataSource1 to gridview etc...
}

private string GetSelectQuery(string table, Dictionary<string, string> parameters)
{
    var query = new System.Text.StringBuilder();
    query.Append(String.Format("SELECT * FROM {0}", table));

    for (int i = 0; i < parameters.Count; i++)
    {
        var param = parameters.ElementAt(i);
        if (i == 0)
            //Add the first parameter
            query.Append(String.Format(" WHERE {0}='{1}' ",param.Key, param.Value));
        else
            query.Append(String.Format(" AND {0}='{1}'", param.Key, param.Value));
    }
    return query.ToString();
}

答案 1 :(得分:0)

请看一下此扩展程序:SqlBuilder Tutorial

使用此扩展,您可以像这样构建动态sql查询。

void DynamicSql(int? categoryId, int? supplierId) { 

   var query = SQL
      .SELECT("ID, Name")
      .FROM("Products")
      .WHERE()
      ._If(categoryId.HasValue, "CategoryID = {0}", categoryId)
      ._If(supplierId.HasValue, "SupplierID = {0}", supplierId)
      .ORDER_BY("Name DESC"); 
}