Issue
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();
The text in txtComment.Text is "bad steak" and the error is incorrect syntax near 'bad' The complete comment reads "06/03/2022 bad steak" I have tried several different ways to write the comment but keep getting the error, always after the date in the string. Any ideas as to what I am doing wrong? Thanks for your help.
Solution
Parameterize the SQL
Fix the using (I use old style syntax for clarity
I used "fake" variables for clarity
This is not fully complete nor is this production ready but should demonstrate the basic principles and resolve your issue.
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(); } }
Answered By - Mark Schultheiss
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.