2011-10-03 169 views
0

我寫的代碼中插入SQL Server中的圖像,但它拋出一個異常:如何從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

+4

問題的第一部分 - 「字符串或二進制數據將被截斷。語句已被終止。」這意味着你的列對於數據來說不夠大,也許它是nvarchar(n),你需要將它改爲max –

+0

如果你使用的是SQL Server 2008 R2(正如這個問題上的標籤所建議的),你可以使用[ NVARCHAR(MAX)](http://msdn.microsoft.com/en-us/library/ms186939.aspx)列將允許[最多2GB](http://msdn.microsoft.com/en-us/庫/ ms176089.aspx)要存儲在其中的數據。 – CraigTP

+0

這些都是很奇怪的建議:這不是字符數據,它是二進制數據。 Nvarchar(任何東西)都是錯的。這裏有一個'image'類型 - 或varbinary或filestream(如果存儲在磁盤上)。除了nvarchar以外的任何東西 –

回答

0

好工作,這個錯誤意味着你的字段(字符串或二進制)的一個數據是超過的數據庫定義將被存儲的列。

這可以是例如您的用戶名。如果數據庫是一個varchar(8)並且你試圖分配一個10個字符的名字,你會得到這個錯誤。

從錯誤消息中,您不能扣除導致錯誤的字段。它可以是任何字符串或二進制數據。用數據庫定義交叉檢查輸入以查找導致錯誤的字段/列。

解決方案:提供較小的數據或增加數據庫中的長度。

0

這裏的問題是,保存圖像的列不夠大,無法保存要插入的圖像。這意味着你將不得不增加它的長度,以便能夠插入你想要的對象。

0

我沒有檢查代碼,但我記得我用過類似的東西。

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