Inserting / updating SQL from C#
Creating an SQL string in C# is a poor way to do it. It might give problems with some special characters, even the data retrieved from SQL to C# might not be the exact same anymore.
You really want to bind your parameters. It prevents SQL attacks, and makes the query run faster.
Here’s a simple piece of code as an example:
1: // we'll assume there's a connection set up in the instance
2:
3: // pass a value
4: public void updateLog(string msg) {
5: // create your command, not the @msg where the parameter will go
6: SqlCommand cmd =
7: new SqlCommand("insert into log(msg) values (@msg)", this.conn);
8:
9: // bind the value to the parameter reference
10: cmd.Parameters.AddWithValue("@msg", msg);
11:
12: // fire
13: try {
14: cmd.Connection.Open();
15: cmd.ExecuteNonQuery();
16: } finally {
17: cmd.Connection.Close();
18: }
19: }