title: Inserting special chars (such as ' or +) into an Access database
body: <p>I have not much experience with SQL, Access nor C# but I find no solution to a problem that should look quite simple for someone who has more expertise. </p>
  
  <p>Basically, the user fill some textboxes in a Winform and he might insert some "special" characters (at least, special for DB strings) such as <code>'</code>. These data are hence transferred into the database through an <code>OleDb</code> connection; let's say that <code>string myString = this.textBox1.Text</code> is the value that I would like to insert into the field <code>MY_FIELD</code> of the table <code>myTable</code>.</p>
  
  <h2>Starting code</h2>
  
  <p>My starting code was straight-forward: </p>
  
  <pre><code>OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + this.DBstring);
  OleDbCommand comm = new OleDbCommand();
  comm.CommandText = "INSERT INTO myTable (MY_FIELD) VALUES ('" + myString + "')";
  comm.CommandType = CommandType.Text;
  comm.Connection = conn;
  conn.Open();
  comm.ExecuteNonQuery();
  conn.Close();
  </code></pre>
  
  <p>The above code will easily fail in the case where <code>myString</code> is something like <code>guns'n'roses</code>, because the <code>comm.CommandText</code> will be the following string value which is not valid SQL: <code>INSERT INTO myTable(MY_FIELD) VALUES ('guns'n'roses')</code>.</p>
  
  <h2>Further research</h2>
  
  <p>I wasn't obviously the first newbie having this kind of problem. So I searched a bit through Stack Overflow and found the following <a href="https://stackoverflow.com/questions/7459360/insert-values-into-an-access-database-that-contain-brackets-braces">thread</a> where a guy had an issue inserting brackets into the command string. Hence, I've tried to adapt my code as for the accepted answer: </p>
  
  <pre><code>comm.CommandText = "INSERT INTO myTable (MY_FIELD) VALUES (?)";
  comm.Parameters.Add(myString);
  </code></pre>
  
  <p>but this raises an <code>InvalidCastException</code> saying that <code>The OleDbParameterCollection only accepts non-null OleDbParameter type objects, not String objects.</code></p>
  
  <p>Could anyone please lead me to what's the best practice to insert any kind of string into the Access database without failing the SQL command due to characters that have a "special" meaning to the SQL interpreter? </p>