2014-10-10 41 views
0

我想將圖像從FileUpload添加到ASP.NET中的本地SQL Server數據庫。將圖像插入到ASP.NET中的本地SQL Server數據庫中

我看了很多同樣的問題,但他們並沒有幫助我:(

int length = FileUpload.PostedFile.ContentLength; 
byte[] picSize = new byte[length]; 

HttpPostedFile uplImage= FileUpload.PostedFile; 

uplImage.InputStream.Read(picSize, 0, length); 

SqlCommand com = new SqlCommand("INSERT INTO [Table] (Name, Picture) values (@Name, @Picture)", con); 
com.Parameters.AddWithValue("@Name", TextName.Text); 
com.Parameters.AddWithValue("@Picture", picSize); 
com.ExecuteNonQuery(); 

所以,如果我只需添加列Name - 所有好的但是當我還想添加圖片到數據庫中存在的錯誤。 :

類型「System.Data.SqlClient.SqlException」的異常出現在System.Data.dll中,但在用戶代碼中沒有處理

附加信息:按鍵附近的語法不正確單詞'圖片'。

在我的本地數據庫Picture有一個image類型。請幫幫我。

+0

你應該看看(http://blogs.msmvps.com/jcoehoorn/blog/ 2014/05/12/can-we-stop-using-addwithvalue-already /)並停止使用'.AddWithValue()' - 它會導致意想不到的結果和令人驚訝的結果... – 2014-10-10 18:50:33

+0

'image'將來會被刪除版本的SQL Server。避免在新的開發工作中使用這種數據類型,並計劃修改當前正在使用它們的應用程序。改用'varbinary(max)'。 [詳細請看這裏](http://msdn.microsoft.com/en-us/library/ms187993.aspx) – 2014-10-10 18:53:25

回答

1

你需要捕捉SqlException,然後處理:[?我們能否停止使用AddWithValue()已經]

int length = FileUpload.PostedFile.ContentLength; 
byte[] picSize = new byte[length]; 
HttpPostedFile uplImage= FileUpload.PostedFile; 
uplImage.InputStream.Read(picSize, 0, length); 

using (SqlConnection con = new SqlConnection(connectionString)) 
{ 
    SqlCommand com = new SqlCommand("INSERT INTO [Table] (Name, Picture) values (@Name, @Picture)", con); 
    try 
    { 
     com.Parameters.AddWithValue("@Name", TextName.Text); 
     com.Parameters.AddWithValue("@Picture", picSize); 
     com.ExecuteNonQuery(); 
    } 
    catch (SqlException ex) 
    { 
     for (int i = 0; i < ex.Errors.Count; i++) 
     { 
      errorMessages.Append("Index #" + i + "\n" + 
       "Message: " + ex.Errors[i].Message + "\n" + 
       "LineNumber: " + ex.Errors[i].LineNumber + "\n" + 
       "Source: " + ex.Errors[i].Source + "\n" + 
       "Procedure: " + ex.Errors[i].Procedure + "\n"); 
     } 
     Console.WriteLine(errorMessages.ToString()); 
    } 
} 
+0

非常感謝! – user3499878 2014-10-10 19:26:35

相關問題