本文共 4291 字,大约阅读时间需要 14 分钟。
本文引用下面的 Microsoft .NET 框架类库名称空间: • System.Data.SqlClient
• System.IO
本任务的内容
• 概要
• 要求
• 创建项目
概要
在 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;
-
- class ExampleOfLegalsoft
- {
- public void OnClick1()
- {
- 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();
- }
-
- public void OnClick2()
- {
- 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 字段的数据保存回文件中。
转载地址:http://ewupi.baihongyu.com/