【问题标题】:What is the use of single and double quotes in SQL? [duplicate]SQL中单引号和双引号有什么用? [复制]
【发布时间】:2019-09-15 17:03:59
【问题描述】:

我将字符串或数字传递给 SQL 查询。

单引号和双引号内的单是什么意思?

select * from college where class = '"+txtclass.Text+"'

select * from college where class = '+txtclass.Text+'

【问题讨论】:

  • @SudiptaMondalm 该链接引发的问题多于答案...
  • 第一个示例似乎脱离了上下文:看起来代码正在连接字符串以进行查询。 (这是错误的做法:应该使用 SQL 参数将参数传递给查询。)
  • @jarlh 我正在使用 SQL 服务器
  • 另外:您应该 NOT 将您的 SQL 与用户提供的值连接起来 - 这是 WIDE OPEN SQL 注入。无论您使用什么数据库系统最有可能都将支持参数化查询之类的东西 - 使用这些可以避免 SQL 注入 - 并使许多与引用相关的问题也消失了
  • @marc_s 看起来这是一个从 C# 中提取的 sn-p。您的编辑可能会混淆这一点。

标签: c# asp.net sql-server quotes


【解决方案1】:

您应该为 SqlCommand 使用参数。

这里有一个小例子说明如何做到这一点:

using (var con = new SqlConnection("conection string"))
{
    con.Open();
    using (var cmd = con.CreateCommand())
    {
        // Here is where we add the parameters into the Sql Query, this way it will prevent SQL Injection
        cmd.CommandText = "select * from college where class = @class";
        // Now we add the value to the parameter @class, I'm assuming here that the column class is a NVarchar
        cmd.Parameters.Add("@class", SqlDbType.NVarChar).Value = txtclass.Text;
        using (var dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                // Do some code
            }
            dr.Close();
        }
    }
}

这个例子是针对Sql的,但是MySql也可以这样,我们只需要使用MySql的类,其他的都一样

注意:我知道这并不能回答所提出的问题,但由于他的做法存在安全风险,我决定举一个简单的例子来提高安全性,因为答案是已经在cmets上给出了问题

【讨论】:

  • 不要使用addwithvalue
  • 嗯谢谢你的警告,我确实使用了 AddWithValue 因为它需要更少的代码。需要进行更多研究,以便我可以更改必须删除 AddWithValue 的解决方案
  • @Camadas 您应该指定字符串参数的大小,否则它可能默认为 1 并静默截断数据。
猜你喜欢
  • 2014-05-13
  • 1970-01-01
  • 2016-06-10
  • 2010-12-31
  • 1970-01-01
  • 2012-02-04
  • 2018-06-19
  • 2017-05-14
相关资源
最近更新 更多