2011-07-02 164 views
1
public void InsertAnImage(Guid i) 
{ 
    StringBuilder sb = new StringBuilder(); 

    sb.Append(""); 

    Stream stream = FileUpload1.FileContent; 
    StreamReader reader = new StreamReader(stream); 

    string myConnectionString = AllQuestionsPresented.connectionString; 
    using (SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString)) 
    { 
     // sample query with parameters to insert into db 
     string sqlQuery = "INSERT INTO [UserProfile] (UserID, Picture) Values (@userId, @picture)"; 
     // conn is your db connection 
     SqlCommand command = new SqlCommand(sqlQuery, conn); 
     // creating parameters 
     SqlParameter paramId = new SqlParameter("@userId", SqlDbType.Int, 4); 
     paramId.Value = 45; 
     // you picture parameter, and assigning its the value 
     SqlParameter paramPicture = new SqlParameter("@picture", SqlDbType.Binary, myImage.Length);// red line here 
     paramPicture.Value = myImage;// red line here 
     // adding params to command 
     command.Parameters.Add(paramId); 
     command.Parameters.Add(paramPicture); 
     // then execute your command 
     command.ExecuteNonQuery(); 
    } 
} 

如何將streamreader而不是Filestream reader放到數據庫中?如何將圖像插入數據庫?

+0

[上傳圖像到SQL Server 2005使用ASP.Net MVC?](http://stackoverflow.com/questions/479699/upload-images-to-sql-server-2005-using-asp-net -mvc) –

+0

我已經在Stack Overflow上回答了同樣的問題,在這裏: - [如何在sql server中存儲圖像?] [1] [1]:http://stackoverflow.com/questions/6449042/如何存儲圖像在SQL服務器/ 6449200#6449200 –

+0

這樣做很少是一個好主意。 我幾乎總是建議將文件存儲在文件系統上並將路徑存儲在數據庫中。這樣可以防止數據庫變得太快,從而使備份,恢復,複製等操作變得更容易。 –

回答