【问题标题】:Incorrect syntax near '='. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception [duplicate]'=' 附近的语法不正确。在 System.Data.SqlClient.SqlConnection.OnError(SqlException 异常 [重复]
【发布时间】:2018-10-30 17:30:46
【问题描述】:

我有问题,当计算其电子邮件的数量列值时,我从 session[“email”] 收到的电子邮件,在我尝试在 int count = (int)cmd.ExecuteScalar(); 捕获错误之前,这是他们的错误消息“'=' 附近的语法不正确。在 System.Data.SqlClient.SqlConnection.OnError(SqlException 异常”。我需要从我的表中计算数量。menu_quantity 的数据类型是浮点数。

 protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["email"] != null)
        {
            A();
            //lbltotalitemcart.Text = A().ToString();
        }
        else
        {
            lbltotalitemcart.Text = "login email first";
        }

    }

 public int A()
    {
        String email = Request.QueryString["email"];
        string stmt = "SELECT COUNT(menu_quantity) FROM cart Where email=" + email + "";
        try
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.
           ConnectionStrings["connectionString"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand(stmt, con))
                {
                    con.Open();
                    int count = (int)cmd.ExecuteScalar();
                    return count;
                }
            }
        }
        catch (Exception e)
        {
            lbltotalitemcart.Text = e.ToString();
            return 0;
        }
    }

【问题讨论】:

  • email 可能是一个字符串,所以你需要email = '" + email + "'...。但与其解决这个问题,不如看看参数化查询,以免面临 sql 注入的风险
  • 与 SQL 注入问题极为相关。 blog.codinghorror.com/…
  • 我得到了答案,更改为字符串 stmt = "SELECT COUNT(menu_quantity) FROM cart Where email=@email";和 cmd.Parameters.AddWithValue("@email", Session["email"].ToString());
  • 必填:xkcd.com/327

标签: c# asp.net sql-server


【解决方案1】:

你在'之前和之后都错过了email

SELECT COUNT(menu_quantity) FROM cart Where email='" + email + "'";

但是它不是执行查询的好方法。相反,使用SqlCommand.Parameters:

string stmt = "SELECT COUNT(menu_quantity) FROM cart Where email=@email"
 using (SqlConnection con = new SqlConnection(ConfigurationManager.
           ConnectionStrings["connectionString"].ConnectionString))
 {
       SqlCommand cmd = new SqlCommand(stmt, con)
       cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = email;
       con.Open();
       int count = (int)cmd.ExecuteScalar();
       return count;
 }

【讨论】:

  • 我个人觉得这个问题的答案不显示使用参数化查询是一个不好的答案
  • 您的代表应该知道答案是使用参数。
  • 我编辑了我的答案;)
【解决方案2】:

我对 ASP 语法不是很熟悉。但我的直觉 SQL 知识告诉我,您在查询本身中缺少围绕电子邮件的引号。

【讨论】:

  • 虽然这绝对是原因,但也应提供纠正 SQL 注入问题的指导。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 2021-01-23
  • 2011-05-28
  • 1970-01-01
  • 2020-11-03
  • 2019-04-13
  • 1970-01-01
相关资源
最近更新 更多