Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 361
Aan Avatar asked Dec 20 '22 21:12

Aan


1 Answers

you should set max size of variable length parameters

replace all varchar (and varbinary) parameters:

command.Parameters.Add(new SqlParameter("v1", SqlDbType.VarChar));

with:

command.Parameters.Add(new SqlParameter("v1", SqlDbType.VarChar, 50));
like image 200
miha Avatar answered Dec 22 '22 09:12

miha