SqlCommand.Prepare method requires all variable length parameters to have an explicitly set non-zero Size

SqlCommand.Prepare method requires all variable length parameters to have an explicitly set non-zero Size

You can should add your parameter like this instead:

command.Parameters.Add(@"v1", SqlDbType.VarChar).Value = TextBox1.Text;
command.Parameters.Add(@"v2", SqlDbType.Int).Value = 0;
command.Parameters.Add(@"v3", SqlDbType.Int).Value = 0;
command.Parameters.Add(@"v4", SqlDbType.VarBinary).Value = FileUpload1.FileBytes;
command.Parameters.Add(@"v5", SqlDbType.VarChar).Value = TextBox3.Text;
command.Parameters.Add(@"v6", SqlDbType.VarChar).Value = TextBox4.Text;
command.Parameters.Add(@"v7", SqlDbType.VarChar).Value = TextBox5.Text;


command.ExecuteNonQuery();

conn.Close();

But personnaly I prefer to add my parameter like this:

cmd.Parameters.AddWithValue(@"v1",  TextBox1.Text);
cmd.Parameters.AddWithValue(@"v2", 0);
cmd.Parameters.AddWithValue(@"v3", 0);
cmd.Parameters.AddWithValue(@"v4", FileUpload1.FileBytes);
cmd.Parameters.AddWithValue(@"v5", TextBox3.Text);
cmd.Parameters.AddWithValue(@"v6", TextBox4.Text);
cmd.Parameters.AddWithValue(@"v7", TextBox5.Text);

SqlCommand.Prepare method requires all parameters to have an explicitly set type

Instead of this:

cmd.Parameters.AddWithValue("@" + key, searchParams[key]);

you need to use something like this:

cmd.Parameters.Add("@" + key, SqlDbType.******).Value = searchParams[key];

You need to be able to somehow determine what datatype your parameters will have to be.

This can be something like:

  • SqlDbType.Int for integer values
  • SqlDbType.VarChar for non-Unicode strings (don't forget the specify a length of the string!)
  • SqlDbType.UniqueIdentifier for Guids
    etc.

Using AddWithValue is convenient - but it leaves it up to ADO.NET to guess the datatype, based on the value passed in. Most of the time, those guesses are pretty good - but at times, they can be off.

I would recommend that you always explicitly say what datatype you want. 

SqlCommand.Prepare method requires all parameters to have an explicitly set type

原文地址:https://www.cnblogs.com/chucklu/p/14388641.html