本文引用下列 Microsoft .NET Framework Class Library 命名空間:
System.Data.SqlClient
System.IO
摘要
GetChunk 和 AppendChunk 方法在 ADO.NET 的 DataReader 列、 DataSet 列、 或 Command 參數中已不可用. 本文描述如何使用 Visual C# .NET 讀寫 binary large object (BLOB) 欄位.
要求
以下是推薦的硬體、軟體、網路結構和服務包要求列表:
Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, 或 Windows NT 4.0 Server
Microsoft Visual Studio .NET
Microsoft SQL Server
建立項目
1. 添加一個名為 MyImages的表到 SQL Server Northwind 資料庫。 表欄位設定如下:
唯一識別欄位名稱為"ID",類型為Int。
名稱為"Description"的VarChar類型的欄位,欄位長度為50。
名稱為"ImgField" 的Image 類型的欄位。
2. 啟動 Visual Studio .NET, 並建立一個新的 Visual C# Windows 應用程式項目。
3. 從工具列中托兩個Button 控制項到預設表單, Form1。
4. 在屬性視窗中修改Button1的 Text 屬性為從檔案儲存到資料庫, 然後修改Button2 的 Text 屬性為從資料庫儲存到檔案。
5. 在代碼視窗的頂部添加下列代碼:
6. using System.Data;
7. using System.Data.SqlClient;
using System.IO;
8. 雙擊 Button1, 並添加下列代碼到 Button1_Click 的事件處理器中:
9.
{
SqlConnection con = new SqlConnection("Server=Darkover;uid=sa;pwd=Password1;database=northwind");
SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("MyImages");
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
FileStream fs = new FileStream(@"C:\winnt\Gone Fishing.BMP", FileMode.OpenOrCreate, FileAccess.Read);
byte[] MyData= new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
da.Fill(ds,"MyImages");
DataRow myRow;
myRow=ds.Tables["MyImages"].NewRow();
myRow["Description"] = "This would be description text";
myRow["imgField"] = MyData;
ds.Tables["MyImages"].Rows.Add(myRow);
da.Update(ds, "MyImages");
con.Close();
}
10. 雙擊 Button2,並添加下列代碼到Button2_Click的事件處理器中:
{
SqlConnection con = new SqlConnection("Server=Darkover;uid=sa;pwd=Password1;database=northwind");
SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("MyImages");
byte[] MyData= new byte[0];
da.Fill(ds, "MyImages");
DataRow myRow;
myRow=ds.Tables["MyImages"].Rows[0];
MyData = (byte[])myRow["imgField"];
int ArraySize = new int();
ArraySize = MyData.GetUpperBound(0);
FileStream fs = new FileStream(@"C:\winnt\Gone Fishing2.BMP", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0,ArraySize);
fs.Close();
}
11. 按 F5 以編譯並運行程式。
12. 點擊 從檔案儲存到資料庫 載入圖象 C:\WinNT\Gone Fishing.bmp 到 SQL Server Image 欄位。
13. 點擊 從資料庫儲存到檔案 以從 SQL Server Image 欄位儲存資料到檔案。