title: Creating safe SQL statements as strings
body: <p>I'm using C# and .NET 3.5. I need to generate and store some T-SQL insert statements which will be executed later on a remote server.</p>
  
  <p>For example, I have an array of Employees:</p>
  
  <pre><code>new Employee[]
  {
     new Employee { ID = 5, Name = "Frank Grimes" },
     new Employee { ID = 6, Name = "Tim O'Reilly" }
  }
  </code></pre>
  
  <p>and I need to end up with an array of strings, like this:</p>
  
  <pre><code>"INSERT INTO Employees (id, name) VALUES (5, 'Frank Grimes')",
  "INSERT INTO Employees (id, name) VALUES (6, 'Tim O''Reilly')"
  </code></pre>
  
  <p>I'm looking at some code that creates the insert statements with String.Format, but that doesn't feel right.  I considered using SqlCommand (hoping to do <a href="https://stackoverflow.com/questions/265192/how-to-get-the-generated-sql-statment-from-a-sqlcommand-object">something like this</a>), but it doesn't offer a way to combine the command text with parameters.</p>
  
  <p>Is it enough just to replace single quotes and build a string?</p>
  
  <pre><code>string.Format("INSERT INTO Employees (id, name) VALUES ({0}, '{1}')",
      employee.ID,
      replaceQuotes(employee.Name)
      );
  </code></pre>
  
  <p>What should I be concerned about when doing this?  The source data is fairly safe, but I don't want to make too many assumptions.</p>
  
  <p>EDIT: Just want to point out that in this case, I don't have a SqlConnection or any way to directly connect to SQL Server.  This particular app needs to generate sql statements and queue them up to be executed somewhere else - otherwise I'd be using SqlCommand.Parameters.AddWithValue()</p>