Error on data insert: String or binary data would be truncated.

Posted by Nisar under Regular Expressions on 9/10/2010 | Points: 10 | Views : 2936 | Status : [Member] | Replies : 1
I upload world document and insert doc info into database.

When i insert recoed into database i got this error on ExecuteNonQuery: String or binary data would be truncated. The statement has been terminated.
This error is due to insert Fileytes field.

Con= new SqlConnection(ConStr);
cmd= new SqlCommand("INSERT INTO Files(FileName,FileBytes) VALUES (@FileName,@FileBytes)",Con);
cmd.Parameters.AddWithValue("@FileName", upFile.FileName);
cmd.Parameters.AddWithValue("@FileBytes", upFile.FileBytes); // Error is due to this line
Con.Open();
cmd.ExecuteNonQuery();
Con.Close();

Database table is like

id int
FileName varchar(50)
FileBytes varbinary(max)

Waiting for reply.
Thanks in advance




Responses

Posted by: SheoNarayan on: 9/11/2010 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
Your code snippets looks good in the first glance and I see you are using AddWithValue method of the SqlCommand object. I would suggest to explicitly specify the data type for at least the Image, specify SqlDbType.Image (its a good practice to not use AddWithValue but to explicitly specify the data type in the Sql Parammeter).

In addition to above you may try following article, however they are not very very different than what you are doing however just give them a try once

http://www.aspfree.com/c/a/ASP.NET/Uploading-Images-to-a-Database--C---Part-I/
http://www.dotnetfunda.com/codes/code375-save-image-in-database-in-net.aspx
http://www.aspnettutorials.com/tutorials/database/Save-Img-ToDB-Csharp.aspx

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Nisar, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response