【问题标题】:SQL server - inserting a string with a single quotation markSQL server - 插入带单引号的字符串
【发布时间】:2013-06-05 03:50:03
【问题描述】:

我遍历外部源并获取字符串列表。然后我使用以下方法将它们插入数据库:

SqlCommand command = new SqlCommand(commandString, connection);
command.ExecuteNonQuery();

commandString 是一个插入命令。即

insert into MyTable values (1, "Frog") 

有时字符串包含 ' 或 " 或 \ 并且插入失败。
有没有一种优雅的方法来解决这个问题(即@"" 或类似的)?

【问题讨论】:

  • 使用参数化查询?

标签: c# sql-server dml


【解决方案1】:

您应该考虑使用参数化查询。这将允许您插入数据,无论内容如何,​​还可以帮助您避免将来可能的 SQL 注入。

http://csharp-station.com/Tutorial/AdoDotNet/Lesson06

http://www.c-sharpcorner.com/uploadfile/puranindia/parameterized-query-and-sql-injection-attacks/

【讨论】:

    【解决方案2】:

    参数。

    insert into MyTable values (@id, @name) 
    

    int id = 1;
    string name = "Fred";
    SqlCommand command = new SqlCommand(commandString, connection);
    command.Parameters.AddWithValue("id", id);
    command.Parameters.AddWithValue("name", name);
    command.ExecuteNonQuery();
    

    现在name 可以有任意数量的引号,它会正常工作。更重要的是,它现在可以安全地免受 sql 注入了。

    像“dapper”这样的工具(在 NuGet 上免费提供)使这更容易:

    int id = 1;
    string name = "Fred";
    connection.Execute("insert into MyTable values (@id, @name)",
        new { id, name });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 2013-01-17
      相关资源
      最近更新 更多