1

I have the following Code in C# ( Sql server (LocalDB)\v11.0) If Definition property has no special character , the Insert executed. but some times it has an unknown special character in it , and i recive the Error.

 for()
  {
  if(){
  DB.Docommand("INSERT INTO Test5(P_Def) VALUES('"+ pro.Definition + "')");
      }
  }

in database the data type is nvarchar(Max) but i receive the following error:

incorrect syntax near .....

I want to insert my property with special characters. What can id do? Thanks

amin
  • 59
  • 7
  • 1
    The short answer is change `VALUES('"+` to `VALUES(N'"+` – mjwills Aug 06 '17 at 11:59
  • 3
    Possible duplicate of [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) – mjwills Aug 06 '17 at 12:00

1 Answers1

5

Parameterize your insert. In addition to gaining an ability to insert strings with any characters that are valid inside nvarchar, you will also fix a major security problem by avoiding a potential sql injection attack:

var cmd = new SqlCommand("INSERT INTO Test5(P_Def) VALUES(@Def)", con);
cmd.Parameters.AddWithValue("@Def", pro.Definition);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523