How can I add user-supplied input to an SQL statement?
<p>I am trying to create an SQL statement using user-supplied data. I use code similar to this in C#:</p>

<pre><code>var sql = "INSERT INTO myTable (myField1, myField2) " +
          "VALUES ('" + someVariable + "', '" + someTextBox.Text + "');";

var cmd = new SqlCommand(sql, myDbConnection);
cmd.ExecuteNonQuery();
</code></pre>

<p>and this in VB.NET:</p>

<pre class="lang-vb prettyprint-override"><code>Dim sql = "INSERT INTO myTable (myField1, myField2) " &amp;
          "VALUES ('" &amp; someVariable &amp; "', '" &amp; someTextBox.Text &amp; "');"

Dim cmd As New SqlCommand(sql, myDbConnection)
cmd.ExecuteNonQuery()
</code></pre>

<p>However,</p>

<ul>
<li>this fails when the user input contains single quotes (e.g. <code>O'Brien</code>),</li>
<li>I cannot seem to get the format right when inserting DateTime values and</li>
<li>people keep telling me that I should not do this because of "SQL injection".</li>
</ul>

<p>How do I do it "the right way"?</p>