0

I have the following statements:

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["DataBaseName"]);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "update Table1 set data = @data where id = @id";
cmd.Parameters.AddWithValue("@data", SqlDbType.VarChar).Value =  data;
cmd.Parameters.AddWithValue("@id", SqlDbType.Int).Value =  id;
cmd.CommandType = CommandType.Text;

try
{
    DataSet ds = new DataSet();
    con.Open();
    cmd.Prepare();
    cmd.ExecuteNonQuery();
    return true;
}

When executing cmd.Prepare() I have an error SqlCommand.Prepare method requires all parameters to have an explicitly set type

I read some answers here, but looks like I did as described here but still have the same problem.

What am I missing?

Community
  • 1
  • 1
gene
  • 2,098
  • 7
  • 40
  • 98
  • 1
    `AddWithValue` does not add with type. It uses the second parameter as a value. You now have two untyped parameters whose values are integers equal to the enum members `SqlDbType.VarChar` and `SqlDbType.Int`. Also you might enjoy reading http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ – GSerg Apr 11 '16 at 16:22
  • Apparently @marc_s made a typo. Replace `AddWithValue` with `Add` and provide length for your varchar. – GSerg Apr 11 '16 at 16:27
  • What should I do in the case if parameter is a `SqlDbType.DateTime` or `Int`? – gene Apr 11 '16 at 19:20
  • Then don't provide length. – GSerg Apr 11 '16 at 20:02

0 Answers0