Search code examples
c#asp.netsql-serverdatabaseparameterized-query

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


I tried to insert some values in SQL database by the code:

var connstring = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString; ;
var conn = new SqlConnection(connstring);
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO [Trainer] (Name, ID, [Trainee Counter], image, [Mobile NO], Email, Password) VALUES(:v1, :v2,:v3,:v4,:v5,:v6,:v7);", conn);

command.Parameters.Add(new SqlParameter("v1", SqlDbType.VarChar));
command.Parameters.Add(new SqlParameter("v2", SqlDbType.Int));
command.Parameters.Add(new SqlParameter("v3", SqlDbType.Int));
command.Parameters.Add(new SqlParameter("v4", SqlDbType.VarBinary));
command.Parameters.Add(new SqlParameter("v5", SqlDbType.VarChar));
command.Parameters.Add(new SqlParameter("v6", SqlDbType.VarChar));
command.Parameters.Add(new SqlParameter("v7", SqlDbType.VarChar));
command.Prepare();
command.Parameters[0].Value = TextBox1.Text;
command.Parameters[1].Value = 0;
command.Parameters[2].Value = 0;
command.Parameters[3].Value = FileUpload1.FileBytes;
command.Parameters[4].Value = TextBox3.Text;
command.Parameters[5].Value = TextBox4.Text;
command.Parameters[6].Value = TextBox5.Text;


command.ExecuteNonQuery();

conn.Close();

But I always get this exception:

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

Actually I have ported this code from one of my C++/CLI project with PostgreSQL, and it works fine on that project.


Solution

  • 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);