在 ADO.NET 中,
DataReader 列、
DataSet 列或
Command 參數不能使用
GetChunk 和
AppendChunk 方法。本文介紹如何使用 Visual C# .NET 讀寫二進制大對象 (BLOB) 字段。
返回頁首
要求
下面的列表列出了推薦使用的硬件、軟件、網絡結構以及所需的 Service Pack:
? |
Microsoft Windows 2000 Professional、Windows 2000 Server、Windows 2000 Advanced Server 或 Windows NT 4.0 Server |
? |
Microsoft Visual Studio .NET |
? |
Microsoft SQL Server |
返回頁首
創建項目
1. |
在您的 SQL Server 羅斯文數據庫中添加一個名為 MyImages 的表。在該表中包含以下字段:
? |
標識字段,名為"ID",類型為 Int。 |
? |
字段,名為"Description",類型為 VarChar,長度為 50。 |
? |
字段,名為"ImgField",類型為 Image。 |
|
2. |
啟動 Visual Studio .NET,然后新建一個 Visual C# Windows 應用程序項目。 |
3. |
將兩個 Button 控件從工具箱拖到默認窗體 Form1 上。 |
4. |
在"屬性"窗口中,將 Button1 的 Text 屬性更改為保存到數據庫(從文件),將 Button2 的 Text 屬性更改為保存到文件(從數據庫)。 |
5. |
將下面的代碼添加到"代碼"窗口頂部: using System.Data;
using System.Data.SqlClient;
using System.IO;
|
6. |
雙擊 Button1,然后將以下代碼添加到 Button1_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");
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();
}
|
7. |
雙擊 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();
}
|
8. |
按 F5 鍵編譯并運行該應用程序。 |
9. |
單擊"保存到數據庫(從文件)",將位于 C:\WinNT\Gone Fishing.bmp 的圖像加載到 SQL Server Image 字段。 |
10. |
單擊"保存到文件(從數據庫)",將 SQL Server Image 字段的數據保存回文件中。 |