【问题标题】:Error: An expression of non-boolean type specified in a context where a condition is expected错误:在预期条件的上下文中指定的非布尔类型的表达式
【发布时间】:2017-08-23 06:01:33
【问题描述】:

我想传递三个查询字符串变量,分别是 DateFrom、DateTo 和 UserName。当我调用该变量时,它显示一个错误:

'在预期条件的上下文中指定的非布尔类型的表达式,靠近'admin'。'"。

我该如何解决这个问题?这是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
        strDate = Convert.ToDateTime(Request.QueryString["DateFrom"]);
        endDate = Convert.ToDateTime(Request.QueryString["DateTo"]);
        UserName = Convert.ToSingle(Request.QueryString["UsName"]);
        string UserName = Request.QueryString["UsrName"];
        string sql;
        sql = ("SELECT * FROM tblReport WHERE Date between'" + strDate + "'and'" + endDate + "'and'" + UserName + "'");
        SqlDataAdapter sda = new SqlDataAdapter(sql, con);
        DataTable dt = new DataTable();
        DataSet dst = new DataSet();
        sda.Fill(dst, "tblReport");
        crypt.Load(@"D:\My Project\Asp.Net\ITApplication\ITApplication\CrystalReport.rpt");
        crypt.SetDataSource(dst);
        CrystalReportViewer1.ReportSource = crypt;
 }

【问题讨论】:

  • 您似乎执行了错误的查询字符串。应该是"SELECT * FROM tblReport WHERE Date between ('" + strDate + "' and '" + endDate + "') and UserName = '" + UserName + "'"(改用参数化查询)。

标签: asp.net sql-server crystal-reports


【解决方案1】:

你在 where 子句中遗漏了一些东西......应该是这样的:

WHERE Date BETWEEN '<FromDate>' AND '<ToDate>' 
AND UserName = '<UserName>'

【讨论】:

    【解决方案2】:

    您的 SQL 字符串格式不正确。

    and 运算符附近放置空格并在between 中使用()

    sql = ("SELECT * FROM tblReport WHERE [Date] between ('" + strDate + "' and '" + endDate + "') and UserName='" + UserName + "'");
    

    旁注

    像这样使用带有连接值的 SQL 字符串是一个非常的坏主意。它使您暴露于 SQL 注入,并且总体上是一种不好的做法。请考虑使用Command.Parameters:

    SqlCommand Command = new SqlCommand("SELECT * FROM tblReport WHERE [Date] between (@strDate and @endDate) and UserName=@UserName");
    Command.Parameters.Add(new SqlParameter("strDate", strDate)); 
    Command.Parameters.Add(new SqlParameter("endDate", endDate)); 
    Command.Parameters.Add(new SqlParameter("UserName", UserName)); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      相关资源
      最近更新 更多