1

I've been having a lot of trouble with these simple lines of code. I tried fixing it many times, but I don't seem to get it. I hope someone can help me with this.

SqlCommand cmd = new SqlCommand("UPDATE dbo.Status SET Status = "<span class=\"label label-success\">Success</span>" WHERE ActivateMember = " +i + "", 
                                mydatabase.cn);

The problem is I'm unable to execute that SqlCommand in C# but I'm able to execute it as a SQL query.

Right now the error is

Unexpected character '\'

2
  • 1
    You need to surround the value with single quotes: "'<span class=\"label label-success\">Success</span>'" but you should really use parameterized queries instead to prevent SQL injection attacks. Commented Jun 8, 2018 at 23:30
  • 1
    SqlCommand usually indicates MS SQL Server, not MySQL. Commented Jun 8, 2018 at 23:50

1 Answer 1

3

Change to use Parameters, it will save you a lot of trouble.

SqlCommand cmd = new SqlCommand("UPDATE dbo.Status SET Status = @status WHERE ActivateMember = @activateMember",mydatabase.cn);
cmd.Parameters.AddWithValue("status", "<span class=\"label label-success\">Success</span>");
cmd.Parameters.AddWithValue("activateMember", i);
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much! I'm sorry as I'm still new in coding.
@CedeeCQ If this answer works for you, don't forget to Accept it as the answer
And it's also worth noting that SqlCommand is IDisposable, so should be in a using block. And unless I'm mistaken, the first parameter to AddWithValue is the name of the parameter, so it should start with an @ (example); but agree it's better not to use AddWithValue anyway, as mentioned above.
@Richardissimo Totally agree with the using block, always a good idea to use a using block if you can. For the Parameter Name though, when adding the parameter it's not necessary to add the '@' prefix. That is only necessary for the parameter name in the Sql statement (or : for Oracle statements)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.