0
string sql = "Insert Into mytable" + $" (Id, Name, otherName) Values" + 
            $" ('{id}','{name}','{otherName}')";
using (SqlCommand cmd = new SqlCommand(sql, sqlConnection))
        {
            cmd.ExecuteNonQuery();
        }

And my problem is: some of my data has things like: in "otherName" columns, which will have some like "Mike's car". SQL server will put error on "'s", which I dont know how to fix on my code.

Thank you for reading. And sorry for my bad English.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
maxrena
  • 501
  • 1
  • 4
  • 14
  • instead of `Mike's car` try `Mike''s car` two single quotes. Whereas you must use Parameterized queries instead. – Mohit S May 08 '17 at 01:22
  • 2
    Possible duplicate of [Pros and Cons of using SqlCommand Prepare in C#?](http://stackoverflow.com/questions/2449827/pros-and-cons-of-using-sqlcommand-prepare-in-c) – Ken Y-N May 08 '17 at 01:23
  • Thanks for the reply, but what I am doing is parsing data from a source which I dont have any control on it. So, I need to figure out how to fix that with code. And by the way, how to parameterize it that way? – maxrena May 08 '17 at 01:30
  • And thank you very much, I appreciate that. – maxrena May 08 '17 at 16:37

1 Answers1

2

You need to use Parameters, you are leaving yourself open to a SQL Injection attack:

// These come from whatever your source which you have no control over.
int id = 12345;
string name = "Andrew";
string otherName = "Fred";

var sql = "Insert Into mytable (Id, Name, otherName) Values (@id, @name, @otherName)
using (var sqlQuery = new SqlCommand(sql, sqlConnection)) 
{

    sqlQuery.Parameters.AddWithValue("@id", id);
    sqlQuery.Parameters.AddWithValue("@name", name);
    sqlQuery.Parameters.AddWithValue("@otherName", otherName);

    sqlQuery.ExecuteNonQuery();
}
Andrew Harris
  • 1,419
  • 2
  • 17
  • 29
  • 1
    Just wanted to add the reason why this is the correct answer: parameters know how to correctly handle (escape) values in such a way that no values can break your SQL command. – Alex Paven May 08 '17 at 09:40
  • Thank you very much, I appreciate your help. – maxrena May 08 '17 at 16:36