【问题标题】:Incorrect syntax near ']'. Unclosed quotation mark after the character string '')' [duplicate]']' 附近的语法不正确。字符串'')'后的非闭合引号 [重复]
【发布时间】:2021-07-11 18:27:40
【问题描述】:

我已经在这个问题上停留了几个小时,我似乎无法克服导致这个问题出现的原因。在调试模式下运行我的应用程序时,它将运行 foreach 两次成功返回“查询已执行!”。

但是,当它第三次运行时,我得到了这个错误:

']' 附近的语法不正确。字符串'')' 后面的未闭合引号。

我的方法将执行插入到 SQL Server 表Logs

static String connectionString = "Data Source=.\\SQLExpress;Database=ElasticSearchService;Trusted_Connection=True;";

        public static async Task<int> InsertLogData()
        {
            SqlConnection connection = null;
            SqlCommand command = null;
            int numrows = 0;

            try
            {
                var response = await _elasticClient.SearchAsync<EsSource>(s => s
                   .Size(3000)
                   .Source(src => src.Includes(i => i
                                     .Fields(f => f.timestamp,
                                             fields => fields.messageTemplate,
                                             fields => fields.message)))
                   .Index("customer-simulation-es-app-logs*")
                   .Query(q => +q
                       .DateRange(dr => dr
                           .Field("@timestamp")
                               .GreaterThanOrEquals("2021-06-07T17:13:54.414-05:00")
                               .LessThanOrEquals(DateTime.Now))));

                // var json = _elasticClient.RequestResponseSerializer.SerializeToString(response);

                connection = new SqlConnection(connectionString);

                Console.WriteLine("\nOpening connection...");

                connection.Open();

                Console.WriteLine("\nConnection successful!");

                foreach (var item in response.Hits)
                {
                    var dateCreated = item.Source.timestamp;
                    var messageTemplate = item.Source.messageTemplate;
                    var message = item.Source.message;


                    command = new SqlCommand("insert into Logs (DateCreated, MessageTemplate, Message) values ('" + dateCreated + "', '" + messageTemplate + "', '" + message + "')", connection); 

                    numrows = command.ExecuteNonQuery();

                    Console.WriteLine("\nQuery Executed!");
                }
                connection.Close();
                Console.WriteLine("\nConnection Closed....");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                command.Dispose();
                connection.Dispose();
            }
            return numrows;
        }

是否有什么导致我没有看到的原因?我的command = new SqlCommand() 是否不正确导致它出现以下错误:

']' 附近的语法不正确。字符串'')' 后面的未闭合引号。

【问题讨论】:

  • 也请学习参数化。现在是 2021 年;SQL 注入现在应该像恐龙一样消亡了。
  • 很可能是由于消息字符串的内容以及您如何插入。字符串内容可能有引号关闭您的插入语句。如果您使用参数,这将不是问题,并且不会受到注入攻击。
  • @Larnu 对不起,我把它放了以防有人想要视觉效果,但我会删除它。
  • 我正在研究 SQL 参数,但是当涉及到它的值部分时,我有点迷茫。当我执行插入的 value() 部分时,是否需要在 SSMS 中进行某种类型的配置才能引用每一列? IE。我的插入是"insert into Logs (DateCreated, MessageTemplate, Message) values()。我可以只做列的名称并在其前面放置一个@,即values(@DateCreated, @MessageTemplate, @Message),还是它应该有一个唯一的名称?如果是这样,我将如何配置它? @penleychan

标签: c# sql-server elasticsearch ssms console-application


【解决方案1】:

对于初学者:

command = new SqlCommand("insert into Logs (DateCreated, MessageTemplate, Message) values (@dt, @mt, @m)";

command.Parameters.AddWithValue("@dt", dateCreated);
command.Parameters.AddWithValue("@mt", messageTemplate);
command.Parameters.AddWithValue("@m", message);

然后执行

在您对此感到满意后,请阅读 this blog - AddWithValue 很方便,但在某些情况下可能会导致性能问题。对于诸如插入语句之类的东西,我不太关心它,但是我建议您阅读博客以了解为什么一旦您对参数化的工作方式感到失望,就应该放弃在 SQL Server 中养成它的习惯.另外值得注意的是,并非每个数据库都存在 AWV 问题,并且在很大程度上,最好使用它并偶尔遇到性能问题,而不是根本不使用参数化并被黑客入侵

SQL 以您获得它的方式(以及我获得它的方式)添加参数等实际上相当乏味。看看 dapper,一个库,它可以让做这类事情变得更容易,比如运行 sql 查询并将结果集转换为 c# 对象列表,有点像解析 Json

其他需要考虑的事项:

  • 使用 ExecuteNonQueryAsync
  • 在 foreach 循环之外创建您的命令,并使用 AddWithValue 添加正确类型的虚拟参数(或利用好机会分支添加正确构造的正确 sql db 类型的参数),然后打开连接并运行循环,在每次循环时更改参数值。总结一下:设置一次,改值,执行1000次,而不是设置1000次
  • 使用using 来声明您的命令,这样它会在以后被释放

【讨论】:

    猜你喜欢
    • 2015-03-20
    • 2011-02-10
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 2017-12-19
    相关资源
    最近更新 更多