【问题标题】:How to insert a string with ( ' ) in to the sql database?如何将带有(')的字符串插入到sql数据库中?
【发布时间】:2019-03-18 06:36:34
【问题描述】:

我有由 ( ' ) 引号组成的字符串,例如“母爱” ...

通过 c# 中的 sql 查询插入数据时。它显示错误。如何纠正问题并成功插入此类数据?

string str2 = "Insert into tblDesEmpOthDetails (EmpID, Interviewnotes) values ('" + EmpId + "','" + Interviewnotes + "')";

采访笔记包含像“母爱”这样的价值(单引号)。执行此查询时,它显示错误为“字符串') 后的未闭合引号”我如何插入这种类型的字符串?

【问题讨论】:

  • 没有SQL数据库这样的东西——SQL只是结构化查询语言,一种语言许多数据库系统都在使用,但不是数据库产品...我们真的需要知道您使用的是什么数据库系统(以及哪个版本)....
  • @Killercam 在这种情况下,我认为我们可以得出结论,OP 正在使用连接来形成查询,在这种情况下,''' 技巧可能是足够的信息是危险的。 参数是这里的正确答案。

标签: c# sql-server


【解决方案1】:

我很确定你不使用 SQL 参数:

using (SqlCommand myCommand = new SqlCommand(
    "INSERT INTO table (text1, text2) VALUES (@text1, @text2)")) {

    myCommand.Parameters.AddWithValue("@text1", "mother's love");
    myCommand.Parameters.AddWithValue("@text2", "father's love");
    //...

    myConnection.Open();
    myCommand.ExecuteNonQuery();
    //...
}

【讨论】:

  • 非常感谢您的正确回答,也是很有价值的回答。
  • @Otiel:此代码是否有效:command.Parameters.AddWithValue("@codes", "'A','B','C'");
  • @user1671639:(如果它没有按预期工作,你应该尝试并提出一个关于 SO 的新问题)是的,我不明白为什么它不起作用。
  • @Otiel:谢谢。我将发布一个关于此的问题。
  • @Otiel:从这个post我找到了答案。
【解决方案2】:

使用命名参数和SqlParameter。

来自http://www.dotnetperls.com/sqlparameter

class Program
{
    static void Main()
    {
        string dogName = "Fido";  // The name we are trying to match.

        // Use preset string for connection and open it.
        string connectionString = 
            ConsoleApplication1.Properties.Settings.Default.ConnectionString;

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // Description of SQL command:
            // 1. It selects all cells from rows matching the name.
            // 2. It uses LIKE operator because Name is a Text field.
            // 3. @Name must be added as a new SqlParameter.
            using (SqlCommand command = 
               new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE @Name", connection))
            {
                // Add new SqlParameter to the command.
                command.Parameters.Add(new SqlParameter("Name", dogName));

                // Read in the SELECT results.
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    int weight = reader.GetInt32(0);
                    string name = reader.GetString(1);
                    string breed = reader.GetString(2);
                    Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}", weight, name, breed);
                }
            }
        }
    }
}

【讨论】:

    【解决方案3】:

    虽然您可以用两个 ' 字符 ('') 替换字符串中的所有 ' 字符,但这不是一个好主意。由于这个问题和许多其他原因(例如避免 SQL 注入攻击),您绝对应该使用命名参数,而不是通过将值直接连接到字符串中来将值添加到您的插入语句中。例如:

    command.CommandText = "Insert into tblDesEmpOthDetails (EmpID, Interviewnotes) values (@EmpId, @Interviewnotes)";
    command.Parameters.AddWithValue("EmpId", EmpId);
    command.Parameters.AddWithValue("Interviewnotes", Interviewnotes);
    

    【讨论】:

      【解决方案4】:

      将此行添加到您尝试输入的字符串中

      说你的字符串是

      string test = "that's not working correctly"
      test = replace(Request.QueryString(test), "'", "''")
      

      那么现在开始测试

      "that''s not working correctly"
      

      这在 SQL 的语法上是正确的

      问候

      【讨论】:

      • 这在技术上是可行的,但却是一种不好的做法。这里正确的方法是使用参数。其他任何事情都是危险的。
      • 虽然这解决了作者的问题,但我不得不反对这是一个可怕的想法。
      • 投反对票;虽然它解决了这个特殊问题,但它留下了更大的问题。
      【解决方案5】:

      作为答案的变体,(非常正确地)指向参数:如果这看起来需要很多工作,那么避免它使用诸如dapper之类的工具:

      int empId = 123;
      string notes = "abc";
      connection.Execute(@"insert into tblDesEmpOthDetails (EmpID, Interviewnotes)
                           values (@empId, @notes)", new {empId, notes});
      

      Dapper 将自动获取 empIdnotes(来自匿名对象)并将它们添加为命名/类型化参数。类似的 Query/Query<T> 扩展方法还允许直接在对象模型中进行简单且高度优化的查询

      【讨论】:

        【解决方案6】:

        你需要使用双''

        INSERT INTO something (Name) VALUES ('O''something''s')
        

        这将插入 O'something's。 我读到的另一个例子是:

        假设我们有一个字符串:

        SQL = "SELECT * FROM name WHERE LastName='" & LastName & "' "
        

        如果我们有 O'Brian、O'Reily 等姓氏,我们会得到类似的字符串

        SELECT * FROM name WHERE LastName='O'Brien'
        

        第二个 ' 将结束 SQL 语句。所以这里最简单的解决方案是使用双 '' 然后我们将有这样的字符串:

        SELECT * FROM name WHERE LastName='O''Brien'
        

        【讨论】:

        • 这在技术上是可行的,但却是一种不好的做法。这里正确的方法是使用参数。其他任何事情都是危险的。
        • 是的,我听说了。我只是写这个简单的考试来解释双''。
        • @JasonPaddle - 如果您努力明确表示不应使用此方法并解释正确的方法,我将删除我的反对票。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多