If you are using ADO.NET much, you have probably come across Parameters by now. They are a clean and elegant way of using SQL, and in many instances, they are the only way to pass data to your server. However, there's a gotcha out there that you need to be aware of. Take a look at the code sample below (I'm using each of the available overloads, going from most generic to most precise, to declare @SomeParam and set its value to 0 - Note also that you could declare the Parameter and then add it to the collection, I just chose to use the simplified syntax):
| SqlCommand cmd = new SqlCommand(); //Add a Parameter and then give it a value cmd.Parameters.Add(); cmd.Parameters[0].Value = 0; //Add a Parameter and give it a value (String, Object) cmd.Parameters.Add("@SomeParam", 0); //Add a Paramater and Specify a type, then add a value (String, DbType) cmd.Parameters.Add("SomeParam", SqlDbType.Int).Value = 0; //Specify a length (String, DbType, Int32) cmd.Parameters.Add("@SomeParam", SqlDbType.Int, 1).Value = 0; //Map it back to a Column cmd.Parameters.Add("@SomeParam", SqlDbType.Int, 1, "TableColumnName").Value = 0; |
| cmd.Parameters.Add("@SomeParam", Convert.ToInt32(0)); |