【问题标题】:Additional information: Incorrect syntax near 's' [closed]附加信息:'s'附近的语法不正确[关闭]
【发布时间】:2016-12-10 22:14:25
【问题描述】:

你能告诉我我的错误在哪里吗?!? 我在任何 's' 附近都找不到任何不正确的语法!。 这是我的代码:

public static DataTable InsertConnect(ComboBox Site , ComboBox server , ComboBox Host , ComboBox Domain , Label Price)
{
    SqlConnection cn = new SqlConnection();
    cn.ConnectionString = Server.Connection;
    cn.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = cn;
    cmd.CommandText = "insert into tblPrice(Site,Server,Host,Domain,Price) 
      values('" + Site.Text + "','" + server.Text + "','" + Host.Text + "','" + Domain.Text + "','" + Price.Text + "')'"; 


    SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, cn);
    DataTable dt = new DataTable();
    da.Fill(dt);
    return dt;
}

【问题讨论】:

  • 为什么最后一个括号后面有'
  • 我真的建议使用参数来避免sql注入,这里简单的例子:stackoverflow.com/questions/17569051/…
  • @J.Pichardo 因为如果我不输入 ' 我将面临错误
  • @VorTex318 最后一个' 没有匹配项,很可能是导致错误的原因,如果不是,则错误可能在您要连接的字符串上,请参阅@Fabio 答案,使用@ 987654325@ 可以修复它。

标签: c# sql-server visual-studio windows-forms-designer


【解决方案1】:

原因是您不使用 SqlParameter 将值传递给查询。
如果您使用了参数,那么您的查询中就不会出现像一些额外的' 字符这样的问题。

始终使用 SqlParameters。

public static DataTable InsertConnect(ComboBox Site , ComboBox server , ComboBox Host , ComboBox Domain , Label Price)
{
    using (var cn = new SqlConnection(Server.Connection))
    {
        cn.Open();

        using (var cmd = new SqlCommand())
        {
            cmd.Connection = cn;
            cmd.CommandText = "insert into tblPrice(Site,Server,Host,Domain,Price) values (@Site, @Server, @Host, @Domain, @Price)"; 
            var parameters = new[]
            {
                new SqlParameter { ParameterName = "@Site", .SqlDbType = SqlDbType.VarChar, .Value = Site.text },
                new SqlParameter { ParameterName = "@Server", .SqlDbType = SqlDbType.VarChar, .Value = server.text },
                new SqlParameter { ParameterName = "@Host", .SqlDbType = SqlDbType.VarChar, .Value = Host.Text },
                new SqlParameter { ParameterName = "@Domain", .SqlDbType = SqlDbType.VarChar, .Value = Domain.Text },
                new SqlParameter { ParameterName = "@Price", .SqlDbType = SqlDbType.VarChar, .Value = Price.Text }
            }
            cmd.Parameters.AddRange(parameters);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();

            da.Fill(dt);
            return dt;
        }
    }
}

然后您可以使用SqlDataAdapter 的构造函数,它以SqlCommand 作为参数,因为您的cmd 包含运行查询所需的所有信息。

【讨论】:

    【解决方案2】:

    问题可能在于包含撇号 (') 的参数之一。尝试打印出cmd.CommandText,你会发现它不是一个有效的SQL命令。

    在相关的说明中,这是 SQL 注入的基础。解决方案是不要通过连接值来构造 SQL 命令,尤其是字符串。相反,使用命令参数并构造参数化命令。

    您可以在 MSDN 上了解更多信息:How to: Execute a Parameterized Query

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2020-11-03
      • 2018-10-25
      • 2013-06-26
      相关资源
      最近更新 更多