尝试将日期插入注释字符串并更新文件时,我不断收到语法错误

I keep getting a syntax error when trying to insert a date into a comment string and updating the file

var dat = DateTime.Now.ToString("MM/dd/yyyy");
comment = dat.ToString();
comment = comment += "  ";
comment = comment += txtComment.Text + NewLine;

ssl = $"update dbo.steak set comment={comment} where fileid={r2}";
using (command = new SqlCommand(ssl, sqlConnection));
command.ExecuteNonQuery();

txtComment.Text 中的文本是“bad steak”,错误是 'bad' 附近的语法错误 完整的评论是“06/03/2022 bad steak” 我尝试了几种不同的方式来编写评论,但始终出现错误,总是在字符串中的日期之后。关于我做错了什么的任何想法?感谢您的帮助。

  • 参数化 SQL

  • 修复使用(为了清楚起见,我使用旧式语法

  • 为了清晰起见,我使用了“假”变量

  • 这还没有完全完成,也没有准备好制作,但应该展示基本原理并解决您的问题。

      var dat = DateTime.Now.ToString("MM/dd/yyyy");
      int r2 = 563; //fake an id
      string sqlComnnection = "sometthing connection";
      string txtComment = "Bad Steak'';drop table dbo.steak--";
      var nowDate = DateTime.Now.ToString("MM/dd/yyyy");
      string comment = $"{nowDate} {txtComment}{Environment.NewLine}";
      var sqlText = @"
          UPDATE dbo.steak 
          SET comment = @comment 
          WHERE fileid = @r2;
          ";
      using (var connection = new SqlConnection(sqlComnnection))
      {
          using (var command = new SqlCommand())
          {
              connection.Open();
              command.Parameters.Add(new SqlParameter("@comment", comment) {SqlDbType = SqlDbType.VarChar});
              command.Parameters.Add(new SqlParameter("@r2", r2) {SqlDbType = SqlDbType.Int});
              command.CommandText = sqlText;
              command.CommandType = CommandType.Text;
              command.ExecuteNonQuery();
          }
      }