C# 如何从SQL Server插入和检索图像?

C# 如何从SQL Server插入和检索图像?,c#,linq,linq-to-sql,exception-handling,sql-server-2008-r2,C#,Linq,Linq To Sql,Exception Handling,Sql Server 2008 R2,我编写了在SQL server中插入图像的代码,但它引发了一个异常: 字符串或二进制数据将被截断。声明已终止 以下是我插入图像的代码: FileStream imageStream = new FileStream(CvVariables.IMAGE_PATH, FileMode.Open, FileAccess.Read); int fileLangth = (int)imageStream.Length; byte[] imageInBytes = new byte[fileLangth];

我编写了在SQL server中插入图像的代码,但它引发了一个异常:

字符串或二进制数据将被截断。声明已终止

以下是我插入图像的代码:

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.NewCustomerTextBoxNationalID.Text,
      Address = this.NewCustomerTextBoxAddress.Text
};
singupDataContext.Cv_Customer_Informations.InsertOnSubmit(addNewCustomer);
singupDataContext.SubmitChanges();
我也不知道如何从SQL Server检索图像


更新:我在UserImage字段中使用图像数据类型,并且我正在使用WPF。这个错误意味着您的一个字段字符串或二进制的数据比存储它的列的数据库定义长

例如,这可以是您的用户名。如果数据库是varchar8,并且您尝试分配一个10个字符的名称,则会出现此错误

从errormessage中,您无法扣除导致错误的字段。它可以是任何字符串或二进制数据。将输入与数据库定义交叉检查,以查找导致错误的字段/列


解决方案:提供较小的数据或增加数据库的长度。

这里的问题是保存图像的列不够大,无法保存插入的图像。这意味着您必须增加它的长度,才能插入您想要插入的对象。

我没有检查代码,但我记得我使用了类似的东西

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

问题的第一部分-字符串或二进制数据将被截断。语句已终止。。这意味着您的列不够大,无法容纳数据,可能是nvarcharn。您需要将其更改为max。如果您使用的是SQL Server 2008 R2,正如此问题上的标记所建议的那样,您可以使用列来存储其中的数据。这些建议非常奇怪:这不是字符数据,而是二进制数据。一切都错了。此文件有一个“映像”类型,或者varbinary,或者filestream(如果存储在磁盘上)。。SQL server中没有长blob和中等blob类型。所以是的,有一个问题——它们不存在。Varbinary和Image是合适的选项