惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

W
WeLiveSecurity
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
Stack Overflow Blog
Stack Overflow Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
IT之家
IT之家
Cloudbric
Cloudbric
The Register - Security
The Register - Security
小众软件
小众软件
PCI Perspectives
PCI Perspectives
G
Google Developers Blog
AI
AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Google DeepMind News
Google DeepMind News
Google DeepMind News
Google DeepMind News
宝玉的分享
宝玉的分享
Recent Commits to openclaw:main
Recent Commits to openclaw:main
量子位
TaoSecurity Blog
TaoSecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
F
Full Disclosure
N
Netflix TechBlog - Medium
博客园_首页
Last Week in AI
Last Week in AI
A
Arctic Wolf
B
Blog RSS Feed
J
Java Code Geeks
C
Cybersecurity and Infrastructure Security Agency CISA
I
InfoQ
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
NISL@THU
NISL@THU
MyScale Blog
MyScale Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Jina AI
Jina AI
有赞技术团队
有赞技术团队
S
Schneier on Security
L
Lohrmann on Cybersecurity
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
P
Palo Alto Networks Blog
S
Security @ Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
Security Latest
Security Latest
Vercel News
Vercel News
博客园 - 司徒正美
Webroot Blog
Webroot Blog
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans

博客园 - 恭喜发财

android 电话状态的监听(来电和去电) (转)Xml DML - 恭喜发财 - 博客园 (转)sql:variable() binding and modify method of xquery: insert XML DML 在WinForm中控制GIF动画的启停的一种方法(转) SQL Server Backup file in standard Zip format c# 得到局域网中可用SqlServer服务器列表(转) C#实现UDP协议(转) 健康大讲堂—凡膳皆药 寓医于食 ReportView(RDSL)参考资料 How To Print Using Custom Page Sizes on Windows NT and Windows 2000(VB6) 汇总c#.net常用函数和方法集 在多线程中如何调用Winform 使用C#在进度条中显示复制文件的进度(转) c#将大文件读取或写入到数据库(带进度条的源码)(转) 写C#自定义控件的心得 Finalize(析构函数)、Dispose、Close 的区别与使用 如何在WinForm中对DataGrid进行分页显示(转) 如何用C#做一个类似于桌面插件的程序(转) c#连接各类数据库大全
Working with binary large objects (BLOBs)
恭喜发财 · 2008-08-19 · via 博客园 - 恭喜发财

sample:WorkingWithBLOBs.zip

Introduction:

You can define a BLOB as a large photo, document, audio etc. saved in binary formats that you want to save in a database.
Saving and retrieving BLOBs in a database is more complex than querying string or numeric data.

The BLOB may be very large and if you try to move it in one piece will consume a lot of system memory and that for sure will affect your application performance.

To reduce the amount of system memory you have to break up the BLOB into smaller pieces.

There are a lot of classes that are designed for moving large amount of binary data like BinaryRader, BinaryWriter which exists in System.IO namespace. In the next paragraphs you will see how to use all of this.

Saving a BLOB value to the database:
 
To save a BLOB value to database we use FileStream and BinaryReader classes.

The next example will show you the process of saving a BLOB to a database.

string filePath = @"D:""My Movie.wmv";

//A stream of bytes that represnts the binary file

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

//The reader reads the binary data from the file stream

BinaryReader reader = new BinaryReader(fs);

//Bytes from the binary reader stored in BlobValue array

byte[] BlobValue = reader.ReadBytes((int)fs.Length);

fs.Close();

reader.Close();

SqlConnection BlobsDatabaseConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");
SqlCommand SaveBlobeCommand = new SqlCommand();

SaveBlobeCommand.Connection = BlobsDatabaseConn;

SaveBlobeCommand.CommandType = CommandType.Text;

SaveBlobeCommand.CommandText = "INSERT INTO BlobsTable(BlobFileName, BlobFile)" + "VALUES (@BlobFileName, @BlobFile)";

SqlParameter BlobFileNameParam = new SqlParameter("@BlobFileName", SqlDbType.NChar);

SqlParameter BlobFileParam = new SqlParameter("@BlobFile", SqlDbType.Binary);

SaveBlobeCommand.Parameters.Add(BlobFileNameParam);

SaveBlobeCommand.Parameters.Add(BlobFileParam);

BlobFileNameParam.Value = filePath.Substring(filePath.LastIndexOf("""") + 1);

BlobFileParam.Value = BlobValue;

try

{

    SaveBlobeCommand.Connection.Open();

    SaveBlobeCommand.ExecuteNonQuery();

    MessageBox.Show(BlobFileNameParam.Value.ToString() + " saved to database.","BLOB Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

catch(Exception ex)

{

    MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

finally

{

    SaveBlobeCommand.Connection.Close();

}Retrieving a BLOB from the database:

To retrieve a BLOB value from database we use FileStream and BinaryWriter classes.

The next example will show you the process of retrieving a BLOB to a database.

NOTE: you will see that we set the CommandBehavior to SquentialAccess when we call ExecuteReader() method, this allow us to use the GetBytes() method of the SqlDataRader, so we can read the BLOB from database in smaller, user-definable amounts.

string
SavePath = @"D:""My BLOBs";

SqlConnection SaveConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");

SqlCommand SaveCommand = new SqlCommand();

SaveCommand.CommandText = "Select BlobFileName, BlobFile from BlobsTable where BlobFileName = @BlobFileName";

SaveCommand.Connection = SaveConn;

SaveCommand.Parameters.Add("@BlobFileName", SqlDbType.NVarChar).Value = "My Movie.wmv";


//the index number to write bytes to

long CurrentIndex = 0;


//the number of bytes to store in the array

int BufferSize = 100;


//The Number of bytes returned from GetBytes() method

long BytesReturned;


//A byte array to hold the buffer

byte[] Blob = new byte[BufferSize];


SaveCommand.Connection.Open();


//We set the CommandBehavior to SequentialAccess

//so we can use the SqlDataReader.GerBytes() method.


SqlDataReader
reader = SaveCommand.ExecuteReader(CommandBehavior.SequentialAccess);


while
(reader.Read())

{

    FileStream fs = new FileStream(SavePath + """" + reader["BlobFileName"].ToString(), FileMode.OpenOrCreate, FileAccess.Write);

    BinaryWriter writer = new BinaryWriter(fs);

    //reset the index to the beginning of the file

    CurrentIndex = 0;

    BytesReturned = reader.GetBytes(1, //the BlobsTable column indexCurrentIndex, // the current index of the field from which to begin the read operationBlob, // Array name to write tha buffer to0, // the start index of the array to start the write operationBufferSize // the maximum length to copy into the buffer); 

    while (BytesReturned == BufferSize)

    {

        writer.Write(Blob);

        writer.Flush();
        CurrentIndex += BufferSize;

        BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);

    } 

    writer.Write(Blob, 0, (int)BytesReturned);

    writer.Flush(); writer.Close(); 

    fs.Close();

}
 

reader.Close();

SaveCommand.Connection.Close();

To fully understand the concept you need to try to write this code yourself.

Note: The database and the full source code in the source code area with this article.