飞艳小屋

程序--人生--哲学___________________欢迎艳儿的加入

BlogJava 首页 新随笔 联系 聚合 管理
  52 Posts :: 175 Stories :: 107 Comments :: 0 Trackbacks

C#中通过使用ADO.NET读写BLOB数据

[日期:2005-02-12] [字体: ]
本文引用下面的 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. 在"属性"窗口中,将 Button1Text 属性更改为保存到数据库(从文件),将 Button2Text 属性更改为保存到文件(从数据库)
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 字段的数据保存回文件中。
posted on 2005-11-17 17:03 天外飞仙 阅读(973) 评论(0)  编辑  收藏 所属分类: .net

只有注册用户登录后才能发表评论。


网站导航: