操作数据库的Blob数据 (文件, 图片等)

使用场景:
数据库里面直接使用blob类型保存图片,文件等二进制文件,如何对这些数据进行插入,读取?

1. 插入: TSQL可以使用Openrowset,Bulk, 例如:

CREATE TABLE [SBLOB] (
[CabData] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

INSERT INTO [SBLOB] ([CabData])
SELECT
BulkColumn FROM OPENROWSET(
Bulk 'C:\MyCab.zip', SINGLE_BLOB) AS BLOB

2. 读取:将数据库值读取为文件
在SQL Server 2000和之前,可以使用TextCopy命令。
但是微软在SQL Server 2005及以后,不再有这个命令。因此比较麻烦。
但是如果用.net可以很方便的实现这个功能。
sample code:

int IndexBlobContents = 0;
sqlconn.ConnectionString = "Server=" + ServerName + ";UID=" + UID + ";Pwd=" + Pwd + ";Database=" + DBName;
sqlconn.Open();

Blobsize = 10000000;// Initalize the BlobSize
cmd = new SqlCommand("SELECT " + Fldnames + " FROM " + TbName + " " + Cndt, sqlconn);
sqlDr = cmd.ExecuteReader();
while (sqlDr.Read())
{
//dirname + filename
ExtractFileName = ExtractPath + sqlDr[1].ToString();
startIndex = 0; // Reset the starting byte for the new BLOB.
outBuffer = new byte[Blobsize];
if (File.Exists(@ExtractFileName))
{
File.Delete(@ExtractFileName);
}

// Create a file to hold the output.
fs = new FileStream(@ExtractFileName, FileMode.OpenOrCreate, FileAccess.Write);
bw = new BinaryWriter(fs);

// Read bytes into outByte[] and retain the number of bytes returned.
blob = sqlDr.GetBytes(IndexBlobContents, startIndex, outBuffer, 0, Blobsize);
while (blob == Blobsize) // Continue while there are bytes beyond the size of the buffer.
{
bw.Write(outBuffer);
bw.Flush();
startIndex += Blobsize;
blob = sqlDr.GetBytes(IndexBlobContents, startIndex, outBuffer, 0, Blobsize);
}

// Write the remaining buffer.
bw.Write(outBuffer, 0, (int)blob);
bw.Flush();
bw.Close();
fs.Close();
}
sqlDr.Close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值