开发者

How to insert and retrieve image from SQL Server?

开发者 https://www.devze.com 2023-04-10 11:41 出处:网络
I have written code to insert an Image in SQL server but it throws an exception: String or binary data would be truncated. The statement has been terminated.

I have written code to insert an Image in SQL server but it throws an exception:

String or binary data would be truncated. The statement has been terminated.

Here is my Code for insert image:

FileStream imageStream = new FileStream(CvVariables.IMAGE_PATH, FileMode.Open, FileAccess.Read);
int fileLangth = (int)imageStream.Length;
byte[] imageInBytes = new byte[fileLangth];
imageStream.Read(imageInBytes, 0, (int)fileLangth);
Cv_Customer_Information addNewCustomer = new Cv_Customer_Information
{
      UserID = this.NewCustomerTextUserName.Text,
      UserImage =new System.Data.Linq.Binary(imageInBytes),
      Date = this.NewCustomerDate.SelectedDate.ToString(),
      Name = this.NewCustomerTextBoxName.Text,
      Phone = this.NewCustomerTextBoxPhone.Text,
      Email = this.NewCustomerTextBoxEmail.Text,
      NationalID = this.NewCustomerText开发者_运维百科BoxNationalID.Text,
      Address = this.NewCustomerTextBoxAddress.Text
};
singupDataContext.Cv_Customer_Informations.InsertOnSubmit(addNewCustomer);
singupDataContext.SubmitChanges();

I also don`t understand how to retrieve images from SQL Server?

update: I use image Data Type in UserImage field and I am working with WPF


Well, this error means that the data of one of your fields (string or binary) is longer than the database definition of the column in which it will be stored.

This can be for example your username. If the database is a varchar(8) and you try to assign a name of 10 characters, you will get this error.

From the errormessage you cannot deduct what field is causing the error. It can be any string or your Binary data. Crosschek the input with the database definition to find the field/columns that is causing the error.

Solution: provide smaller data or increase the length in the database.


The problem here is that the column that is holding your image is not big enough to hold the image you are inserting. This means that you will have to increase its length in order to be able to insert the object you want to.


I haven't checked the code but I remember that I used something similar.

Image image;
using (MemoryStream stream = new MemoryStream(imageByteArray,0,imageByteArray.Length)) 
{ 
    stream.Write(imageByteArray,0,imageByteArray.Length); 
    image = Image.FromStream(stream,true); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号