0

我在后面的代码中有以下代码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";  

我希望当用户不填写某些文本框时,在查询中,文本框的条件在查询中被忽略。我希望你明白我想要什么。

4

2 回答 2

2

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

这是 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();
}
于 2012-12-25T17:25:02.587 回答
0

看看这个扩展:SqlBuilder 教程

使用此扩展,您可以像这样构建动态 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"); 
}
于 2012-12-25T17:08:14.610 回答