欢迎投稿

今日深度:

使用SQL Server 2008的FILESTREAM特性管理文件(1)(3)

使用FILESTREAM读取数据

在C#项目的默认表单上,添加一个按钮,命名为btnReadFile,在click事件中插入清单2中的代码。

清单2 使用FILESTREAM读取数据。这个click事件处理程序从数据库读取FILESTREAM列中的内容。

private void btnReadFile_Click(object sender, EventArgs e)
{
string connectionString =  ConfigurationManager.ConnectionStrings
["fileStreamDB"].ConnectionString;               
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
//Get the PathName of the File from the database
command.CommandText = "SELECT Picture.PathName(), "
+ "GET_FILESTREAM_TRANSACTION_CONTEXT() FROM Product "
+ "WHERE ProductID = 1";
SqlTransaction transaction =
connection.BeginTransaction(IsolationLevel.ReadCommitted);
command.Transaction = transaction;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{                       
string path = reader.GetString(0);
SqlFileStream stream = new SqlFileStream(path,
(byte[])reader.GetValue(1),FileAccess.Read,
FileOptions.SequentialScan, 0);                       
lstResults.Items.Clear();
int length = (int) stream.Length;
byte[] contents = new byte[length];
stream.Read(contents,0,length);                    
string results = System.Text.Encoding.ASCII.GetString
(contents);
lstResults.Items.Add(results);
stream.Close();
}
}
transaction.Commit();
}
}       

为了简单起见,我只讨论与前面不同的代码,当你创建一个SqlFileStream时,你需要指出你打开的文件流:

SqlFileStream stream = new SqlFileStream(path,
(byte[])reader.GetValue(1),FileAccess.Read,
FileOptions.SequentialScan, 0);

接下来,读取文件流的内容,转换成字节数组,再转换成字符串,最后在列表框ListBox)中显示出来:

int length = (int) stream.Length;
byte[] contents = new byte[length];
stream.Read(contents,0,length);                    
string results = System.Text.Encoding.ASCII.GetString
(contents);
lstResults.Items.Add(results);

当你运行这个应用程序时,你会看到一个类似于图2的屏幕,当你点击“写入文件”按钮时,应用程序把文本框TextBox)中的内容写入到文件流中;当你点击“读取文件”按钮时,应用程序从文件流读取内容,将其显示在列表框ListBox)中。

图2 示例项目-通过使用SqlFileStream类读取和写入FILESTREAM列中的内容

接下来的例子显示如何扩展现有数据库中的文件流。

使用FILESTREAM追加数据

增加一个命令按钮,命名为btnAppendFile,使用清单3中的代码作为它的click事件处理程序代码。

清单3 使用FILESTREAM追加数据

FILESTREAM. 
private void btnAppendFile_Click(object sender, EventArgs e)
{
string connectionString =  
ConfigurationManager.ConnectionStrings
["fileStreamDB"].ConnectionString;                          
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
//Get the PathName of the File from the database
command.CommandText = "SELECT Picture.PathName(), "
+ "GET_FILESTREAM_TRANSACTION_CONTEXT() FROM Product "
+ "WHERE ProductID = 1";
SqlTransaction transaction =
connection.BeginTransaction(IsolationLevel.ReadCommitted);
command.Transaction = transaction;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string path = reader.GetString(0);                       
SqlFileStream stream = new SqlFileStream(path,
(byte[])reader.GetValue(1), FileAccess.ReadWrite,
FileOptions.SequentialScan, 0);
stream.Seek(0, SeekOrigin.End);
string contents = txtInput.Text;
stream.Write((System.Text.Encoding.ASCII.GetBytes
(contents)), 0, contents.Length);                       
stream.Close();
}
}
transaction.Commit();
}
MessageBox.Show("File contents successfully appended");
}

这次当你实例化SqlFileStream对象时,将文件访问权设为ReadWrite,因此你可以读取和写入文件流。

SqlFileStream stream = new SqlFileStream(path,
(byte[])reader.GetValue(1), FileAccess.ReadWrite,
FileOptions.SequentialScan, 0);

然后移动文件流的指针到文件末尾,这样你就可以追加数据了:

stream.Seek(0, SeekOrigin.End);

接下来使用SqlFileStream.Write()方法将用户输入的内容写入到文件流中:

stream.Write((System.Text.Encoding.ASCII.GetBytes
(contents)), 0, contents.Length);   

最后调用SqlTransaction.Commit()方法提交事务。

FILESTREAM的优点

这就是全部过程,现在你可以读取、写入和追加数据到数据库管理的文件中了,虽然这个过程可能比使用文件或在BLOB中存储数据更复杂一些,你会发现使用数据库来管理文件由许多好处。

◆ 使用单个数据存储就可以同时访问非关系和关系数据。

◆ 在数据库备份和还原期间SQL Server自动包括非关系数据BLOB)。

◆ 没有文件大小限制,varbinary(max)数据类型最大不能超过2GB,唯一受限的就是NTFS文件系统上的可用空间。

◆ 你可以在单个事务中同时插入、更新和删除关系数据和非关系数据。

◆ 使用FILESTREAM效率更高,因为SQL Server不再使用缓冲区内存操作非关系数据BLOB)。

◆ 你可以使用ADO.NET在中间层代码直接访问非关系数据,不用再求值于独立的API了。

◆ 依赖于文件大小,NTFS文件系统可以比SQL Server更快地保存和检索大型BLOB。

本文向你展示了如何实现新的FILESTREAM特性,正如你所看到的,当你想在一个事务中同时存储关系数据和非关系数据时,FILESTREAM提供了一个易于使用的事务编程模型。

原文:Managing Files with SQL Server 2008's FILESTREAM Feature        

作者:Thiru Thangarathinam

51CTO独家译稿,合作站点转载请注明原文译者和出处为51CTO.com】

  1. SQL Server 2008 的恢复和备份模式
  2. SQL Server 2008新特性——FILESTREAM
  3. 视频教程下载:SQL Server 2008 的安全性改进


www.htsjk.Com true http://www.htsjk.com/shujukugl/18099.html NewsArticle 使用FILESTREAM读取数据 在C#项目的默认表单上,添加一个按钮,命名为btnReadFile,在click事件中插入清单2中的代码。 清单2 使用FILESTREAM读取数据。这个clic...
评论暂时关闭