2013-07-23 158 views
-2

我有一個表(像,名稱,圖像),我想知道如何存儲和更新數據庫中的圖像。我使用OpenFileDialog讀取圖像,希望能幫助我朋友。如何使用C#窗體形式在sql中存儲圖像

+1

這會告訴你一個例子:http://www.codeproject.com/Articles/21208/Store-or-Save-images-in-SQL-Server – Zaki

+0

你正在使用哪個數據庫!? –

+0

作爲'VARBINARY(MAX)'或同等學歷。或者,你在尋找代碼嗎? (如果是這種情況,你必須給我們多一點的工作空間) –

回答

-1

你需要的圖像序列化到可以存儲在SQL BLOB列二進制格式 看看this

+0

y downvote ?? – Rohit

0

試試這個

CREATE TABLE [dbo].[Employee](
    [emp_id] [int] NOT NULL, 
    [emp_name] [varchar](50) NOT NULL, 
    [emp_image] [image] NULL 
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 


string fileName = @"D:\MyImage.jpg"; 
string connectionString = "Password=PWD;Persist Security " + 
    "Info=True;User ID=USER;Initial Catalog=DATABASE;Data Source=SQLSERVER"; 
using (SqlConnection sqlConnection = new SqlConnection(connectionString)) 
{ 

    FileInfo finfo = new FileInfo(fileName); 

    byte[] btImage = new byte[finfo.Length]; 
    FileStream fStream = finfo.OpenRead(); 

    fStream.Read(btImage, 0, btImage.Length); 
    fStream.Close(); 


    using (SqlCommand sqlCommand = new SqlCommand(
     "INSERT INTO Employee (emp_id, emp_name, " + 
     "emp_image) VALUES(@emp_id, @emp_name, @emp_image)", 
     sqlConnection)) 
    { 

     sqlCommand.Parameters.AddWithValue("@emp_id", 2); 
     sqlCommand.Parameters.AddWithValue("@emp_name", "Employee Name"); 
     SqlParameter imageParameter = 
      new SqlParameter("@emp_image", SqlDbType.Image); 
     imageParameter.Value = btImage; 

     sqlCommand.Parameters.Add(imageParameter); 

     sqlConnection.Open(); 
     sqlCommand.ExecuteNonQuery(); 
     sqlConnection.Close(); 
    } 

} 

Reference

+0

@ user2536447你想要什麼? – Amit

+0

也是我的真實表格中包含大約40列是否有另一種方式來存儲圖像(意味着直接或更容易)以及如何在保存後更新圖像 – user2536447

+0

是先更新圖像後創建記錄 – Amit

0

一推薦的將圖像存儲到sql中或從sql中檢索圖像的方法是使用Base64格式。

您可以將圖像轉換爲base64字符串,將其保存爲sql。從sql獲取base64字符串,並將其轉換回圖像。

Here是您如何執行這兩種轉換的鏈接。

0

你可以在表中的數據類型字段是VARBINARY(MAX),那麼你可以使用C#

using (MemoryStream ms = new MemoryStream()) 
{ 
    picturePictureEdit.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 
        c.Picture = ms.ToArray(); 
} 

保存在MS SQL的形象,如果你得到的圖像,從表中可以編寫代碼

if (c.Picture != null) 
{ 
     byte[] newbit = c.Picture.ToArray(); 
     MemoryStream mem = new MemoryStream(newbit); 
     picturePictureEdit.Image = new Bitmap(mem); 

} 

else 
{ 
picturePictureEdit.Image = null; 
} 
相關問題